Bool --6ren">
gpt4 book ai didi

haskell - 如何在 Haskell 中创建函数的字符串表示。如何以奇特的方式打印函数?

转载 作者:行者123 更新时间:2023-12-04 14:31:49 24 4
gpt4 key购买 nike

我的目标是能够将 bool 表达式表示为字符串,例如 "True or False is True" .为了使它成为可能,我首先做了一些 bool 谓词:

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 中以奇特的方式打印函数?

最佳答案

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

关于haskell - 如何在 Haskell 中创建函数的字符串表示。如何以奇特的方式打印函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68507453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com