首页 > 解决方案 > 如何在 Haskell 中创建函数的字符串表示。如何以花哨的方式打印功能?

问题描述

我的目标是能够将布尔表达式表示为字符串,例如"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

在那之后,我决定制作一个将函数映射到字符串的函数。我依靠 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"

GHC 认为函数名是参数名,一般情况下只考虑第一个定义。对于剩余的行,GHC 会发出“模式匹配是多余的”的警告。这是一个运行repr函数的例子:

*LogicH99> repr equ'
"and"

预期的"equivalent to"

是否可以在 Haskell 中以奇特的方式打印函数?

标签: haskelltostring

解决方案


对于一般功能,没有。但是对于 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"

推荐阅读