为什么没有函数的 Show 实例? [英] Why is there no Show instance for functions?
问题描述
只是一个简单的概念性问题,我目前正在尝试更好地学习和理解 Haskell.
Just a quick conceptual question, I am currently trying to learn and understand Haskell better.
我知道 Show 函数用于将值转换为字符串,但为什么函数类型不能与 show 一起使用?
I know the Show function is used to convert values to strings, but why can't function types be used with show?
Prelude> (x -> x*3)
<interactive>:7:1:
No instance for (Show (a0 -> a0))
arising from a use of `print'
Possible fix: add an instance declaration for (Show (a0 -> a0))
In a stmt of an interactive GHCi command: print it
Prelude>
推荐答案
不是他们不能,而是通常没有充分的理由这样做.
It's not that they can't, but that there's not usually a good reason to.
但如果您愿意,绝对可以:
But if you'd like, you definitely can:
Prelude> :{
Prelude| instance Show (a -> b) where
Prelude| show _ = "A function."
Prelude| :}
Prelude> print (x -> x + 7)
A function.
Prelude> print (a b c -> a + b + c)
A function.
如果您想显示
函数的文本表示,那么 - 您不能那样做.与 Ruby、JS 等元编程语言不同,Haskell 对其内部结构知之甚少.
If you'd like to show
the textual representation of the function, well - you can't do that. Unlike metaprogramming languages like Ruby, JS, etc, Haskell code very little knowledge of its own internals.
这篇关于为什么没有函数的 Show 实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!