haskell - 如何在 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 中以奇特的方式打印函数?
解决方案
对于一般功能,没有。但是对于 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"
推荐阅读
- java - 如何初始化在另一个类中定义的数组?
- python - PYTHON:过滤数据集并截断日期
- powershell - 如何从 Powershell 中的字符串中删除一个字符
- python - Python解释循环
- cordova - 将 ionic-webview 插件版本从 1.2.1 更新到 4.1.3 时丢失本地存储数据
- javascript - 量角器无法从 JS 文件中找到函数
- symfony - Symfony 3.4 防火墙配置,带有多个防火墙和多个共享保护身份验证器
- html - 如何让 td 占据 tr 的 50%
- c++ - 根据模板参数将函数标记为 noexcept
- python - 如何使 numba(nopython=true) 与元素数量未知的 1D numpy.ndarray 输入一起工作