我的目标是能够将布尔表达式表示为字符串,例如"True or False is True". 为了使它成为可能,我首先做了一些布尔谓词:
and' :: Bool -> Bool -> Bool
and' p q = p && q
or' :: Bool -> Bool -> Bool
or' p q = p || q
-- ... same for nor, nand, xor, imply and equivalent
equ' :: Bool -> Bool -> Bool
equ' p q = p == q
Run Code Online (Sandbox Code Playgroud)
之后,我决定制作一个将函数映射到字符串的函数。我依赖于 Haskell 的模式匹配功能,但我的技巧没有奏效。
-- representation function, a.k. "show" for functions
repr :: (Bool -> Bool -> Bool) -> [Char]
repr and' = "and"
repr or' = "or"
repr nand' = "nand"
repr nor' = "nor"
repr xor' = "xor'"
repr impl' = "implies"
repr equ' = "equivalent to"
repr other = error "No representation for the given predicate"
Run Code Online (Sandbox Code Playgroud)
GHC 认为函数名是参数名,只将第一个定义视为一般情况。对于剩余的行,GHC 会发出“模式匹配是多余的”警告。这是运行repr函数的示例:
*LogicH99> repr equ'
"and"
Run Code Online (Sandbox Code Playgroud)
预期的 "equivalent to"
是否可以在 Haskell 中以奇特的方式打印函数?
对于一般的功能,没有没有。但是对于 type 的函数,Bool -> Bool -> Bool可能性很少,通过执行以下操作来穷举所有输入是可行的:
repr f = case (f False False, f False True, f True False, f True True) of
(False, False, False, True) -> "and"
(False, True, True, True) -> "or"
-- ...
(True, False, False, True) -> "equivalent to"
_ -> error "No representation for the given predicate"
Run Code Online (Sandbox Code Playgroud)