有没有办法show
Haskell 中的函数列表?当我尝试
ghci> let functions = [(+), (-), (*)]
ghci> functions
GHCi 说:
<interactive>:17:1:
No instance for (Show (Num a0 => a0 -> a0 -> a0))
arising from a use of 'print'
Possible fix:
add an instance declaration for (Show (Num a0 => a0 -> a0 -> a0))
In a stmt of an interactive GHCi command: print it
我不确定如何为此添加实例声明。任何帮助将不胜感激。谢谢。
最佳答案
你不能轻易地展示一个功能。标准答案是
instance Show (a -> b) where
show _ = "<function>"
Prelude> [(+), (-), (*)]
[<function>,<function>,<function>]
这让您有一个展示实例但不提供任何有用的信息。这通常是正确的,因为可能没有紧凑的方式来显示函数的效果。此外,值得注意的是,虽然标准做法是考虑无法显示
的函数,但如果您确实定义了该实例,您可能会像 这样的任何实例一样获得重叠的实例条件instance (...) => Show (a -> b)
既是孤儿又非常一般。经验法则应该是它在应用程序代码中没问题,但在库中很危险。
但有了它,我们可以为 instance Show (a -> b)
制作更好的函数。
如果你知道你的函数有一个有界输入,那么你可以做得更好
-- | A type instantiates 'Universe' if 'universe' is a
-- list of every value instantiating the type
class Universe a where
universe :: [a]
instance Universe Bool where
universe = [True, False]
instance (Universe a, Show a, Show b) => Show (a -> b) where
show f = show $ map (\a -> (a, f a)) universe
Prelude> (&&)
[ (True, [ (True,True)
, (False,False)
])
, (False, [ (True,False)
, (False,False)
])
]
最后,如果可接受的话,我们可以使用 Data.Typeable
机制为函数获得更好的摘要 show
。
import Data.Typeable
instance (Typeable a, Typeable b) => Show (a -> b) where
show f = "{ Function :: " ++ (show $ typeOf f) ++ " }"
Prelude Data.Typeable> [(+), (-), (*)]
[ { Function :: Integer -> Integer -> Integer }
, { Function :: Integer -> Integer -> Integer }
, { Function :: Integer -> Integer -> Integer }
]
但请注意,这将在多态函数上失败。
Prelude Data.Typeable> ($)
<interactive>:7:1:
No instance for (Typeable b0) arising from a use of `print'
The type variable `b0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance [overlap ok] Typeable ()
-- Defined in `Data.Typeable.Internal'
instance [overlap ok] Typeable Bool
-- Defined in `Data.Typeable.Internal'
instance [overlap ok] Typeable Char
-- Defined in `Data.Typeable.Internal'
...plus 18 others
In a stmt of an interactive GHCi command: print it
Prelude Data.Typeable> ($) :: (() -> ()) -> () -> ()
{ Function :: (() -> ()) -> () -> () }
关于haskell - 显示 Haskell 中的函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20848348/