【发布时间】:2013-12-21 01:40:27
【问题描述】:
如果这是一个愚蠢的问题,请原谅我,但是是否有代表所有功能的类型类?比如,假设我有这样的类型
data Foo a = Thing a
instance (Show a) => Show (Foo a) where
show (Thing a) = show a
我想显示Thing (\x -> 1)。也许对漂亮地打印一些关于此的元数据的方法进行某种反思?
试了会出现以下错误
> Thing (\x -> 1)
<interactive>:113:1:
No instance for (Show (t0 -> a0)) arising from a use of `print'
Possible fix: add an instance declaration for (Show (t0 -> a0))
In a stmt of an interactive GHCi command: print it
<interactive>:113:14:
No instance for (Num a0) arising from the literal `1'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
instance Integral a => Num (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus 11 others
In the expression: 1
In the first argument of `Thing', namely `(\ x -> 1)'
In the expression: Thing (\ x -> 1)
这是有道理的,因为t0 -> a0 没有show 的实例,但我不确定如何描述这个类型类的实例?
这不是为了任何制作,我只是在玩 Haskell,好奇我能做什么,不能做什么。
【问题讨论】:
-
如果你想要一个占位符实例以便显示函数然后导入
Text.Show.Functions。 -
酷,谢谢!我知道我错过了什么。
-
函数不能是
Show的实例。看起来很容易,但是对于编译器来说,在编译、优化和组装之后很难获得信息。甚至可以在运行时创建新函数,所以这让事情变得相当复杂。您可能会使用模板 haskell 来管理它,该模板会生成像data Func a = Func a String这样的类型值,其中函数定义可以被推入字符串中,而函数本身则位于a插槽中。然后,您可以为其创建一个简单的Show实例。但这很难写。 -
好的,谢谢。这是有道理的,我不确定这是否可能。感谢您的回答
-
还有一个 answer 到其他地方,他们使用
Control.Category向函数添加名称并使用.组合它们。或者,您可以使用Data.Data的typeOf创建一个Show实例,它只告诉您函数的类型,但这不适用于多态函数。