简体   繁体   中英

Haskell datatype syntax with manipulation, second part

Returning a datatype. For instance, let's say that I had made a datatype:

data Something = Something Int [Char]

And, then I did some manipulation with the following function (the exact function of which is irrelevant):

manipulativeFunc::Something->[Something]

I keep getting these strange error messages that

Top level:
    No instance for (Show (Int -> IO ()))
        arising from use of 'print' at Top level
    Probable fix: add an instance declaration for (Show (Int -> IO ()))
    In a 'do' expression: print it

Note that I don't have any uses of print anywhere in my program, nor do I have any uses of IO. The data declaration and the manipulativeFunc are all I have on it.

What could I be doing wrong?

EDIT: From commenters, I get the message that I may need to declare a Show instance for this task. So, what if I had

data Something = Something Int Int

Then how would I write a Show instance function for it?

Every time you evaluate an expression in ghci, ghci will print the result of that expression. If the expression has a type which can't be printed, you get the above error message.

So the problem is that you entered an expression of type Int -> IO () , which ghci can't print because it's a function.

In order to use the function print , the compiler needs to be able to convert a value into a String , which is ensured by the Show class. You try to display a function, and there is no Show instance defined for it.

In order to be able to display your Something , use

data Something = Something Int [Char] deriving Show

manipulativeFunc can't be displayed that way, but its result if you call it with an argument.

You can use a default Show instance:

data Something = Something Int Int deriving Show

or you can define your own:

instance Show Something where
    show (Something a b) = "<" ++ show a ++ " " ++ show b ++ ">"

But your problem is not related to Something not having a Show instance.

Please clarify whether you use ghc , runhaskell or ghci , and try to provide a complete minimal example. The following code works:

module Aaa where

data Something = Something Int Int

manipulativeFunc::Something->[Something]
manipulativeFunc x = [x]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM