haskell - 显示 Haskell 中的函数列表

标签 haskell

有没有办法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/

相关文章:

haskell - Haskell 中的种类文字

postgresql - haskell-postgres --> 连接参数不是查询

haskell - attoparsec: "nested"parsers -- 使用不同的解析器解析输入的子集

haskell - 什么是在线可用的最好的 haskell 文档?

haskell - 如何在Haskell中读取目录中的所有文件

haskell - 如何使用函数依赖和存在量化来为我的类型删除不必要的参数

haskell - 有没有办法让parsec报告 "shift-reduce"冲突?

Haskell 懒惰 - 我如何强制 IO 更快发生?

haskell - 使用 isPrefixOf 过滤元组列表

haskell - 如何在实物签名中要求功能依赖?