我正在尝试为haskell运算符或函数创建一个Show实例,但我无法弄清楚如何...
我试过
instance (Show (+)) where
show (+) = "+"
但当然,它不起作用。有谁知道怎么做?
答案 0 :(得分:4)
这可能不是您正在寻找的,但它可能是您可以获得的最接近的:我们总是可以将类型类签名转换为具体的数据类型。
-- built it
class Num a where
(+) :: a -> a -> a
(*) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
fromInteger :: Integer -> a
-- ours
data Num
= Plus Num Num
| Mult Num Num
| Subt Num Num
| Neg Num
| Abs Num
| Signun Num
| FromInt Integer
deriving ( Show )
instance Num Num where
(+) = Plus
(-) = Subt
(*) = Mult
negate = Neg
abs = Abs
signum = Signum
fromInteger = FromInt
现在我们可以使用deriving ( Show )
数据类型的Num
位来查看表达式。
>>> 3 + 2 :: Num
Plus (FromInt 3) (FromInt 2)
但通常没有比这更简单的方法来显示Haskell函数或运算符。通常,当您获得类似a -> b
类型的值时,您可以做的最好的事情就是为它提供a
s
instance Show a => Show (Bool -> a) where
show f = "Fun { True -> " ++ show (f True) ++ ", False -> " ++ show (f False) ++ " }"
>>> id :: Bool -> Bool
Fun { True -> True, False -> False }
>>> not
Fun { True -> False, False -> True}