Haskell 数据类型语法与操作,第二部分
返回数据类型。 例如,假设我创建了一个数据类型:
data Something = Something Int [Char]
然后我使用以下函数进行了一些操作(其确切函数无关紧要):
manipulativeFunc::Something->[Something]
我不断收到这些奇怪的错误消息,
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
请注意,我没有任何用途我的程序中的任何地方都没有打印,我也没有使用 IO。数据声明和manipulativeFunc就是我所拥有的全部内容。
我可能做错了什么?
编辑:从评论者那里,我收到消息说我可能需要为此任务声明一个 Show 实例。那么,如果我有
data Something = Something Int Int
那么我将如何为其编写一个 Show 实例函数呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了使用函数
print
,编译器需要能够将值转换为String
,这是由Show
类保证的。您尝试显示一个函数,但没有为其定义Show
实例。为了能够显示您的
Something
,使用manipulativeFunc
不能以这种方式显示,但如果您使用参数调用它,则会显示其结果。In order to use the function
print
, the compiler needs to be able to convert a value into aString
, which is ensured by theShow
class. You try to display a function, and there is noShow
instance defined for it.In order to be able to display your
Something
, usemanipulativeFunc
can't be displayed that way, but its result if you call it with an argument.每次在 ghci 中计算表达式时,ghci 都会打印该表达式的结果。如果表达式具有无法打印的类型,您将收到上述错误消息。
所以问题是您输入了
Int -> 类型的表达式。 IO ()
,ghci 无法打印它,因为它是一个函数。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.您可以使用默认的 Show 实例:
或者您可以定义自己的实例:
但是您的问题与没有 Show 实例的 Something 无关。
请澄清您是否使用
ghc
、runhaskell
还是ghci
,并尝试提供完整的最小示例。以下代码有效:You can use a default Show instance:
or you can define your own:
But your problem is not related to Something not having a Show instance.
Please clarify whether you use
ghc
,runhaskell
orghci
, and try to provide a complete minimal example. The following code works: