繁体   English   中英

显示Haskell中的功能列表

[英]Show a list of functions in 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>]

它使您拥有一个显示实例,但不提供有用的信息。 这通常是正确的,因为可能没有紧凑的方式来显示功能的效果。 此外,值得注意的是,虽然通常的做法是将函数视为无法show ,但如果您确实定义了该实例,则可能会像instance (...) => Show (a -> b) a- instance (...) => Show (a -> b)既是孤儿又很笼统。 经验法则应该是应用程序代码可以,但是在库中是危险的。

但是,通过这种方式,我们可以使instance Show (a -> b) a- 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 ,我们可以使用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 :: (() -> ()) -> () -> () }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM