考虑以下情况。我定义了一个函数来处理元素列表,方法是在头部执行操作并在列表的其余部分调用函数。但是在元素的某些条件下(为负数,作为特殊字符,......)我在继续之前更改列表其余部分的符号。像这样:
f [] = []
f (x : xs)
| x >= 0 = g x : f xs
| otherwise = h x : f (opposite xs)
opposite [] = []
opposite (y : ys) = negate y : opposite ys
如
opposite (opposite xs) = xs
,我变成了冗余相反操作的情况,累积opposite . opposite . opposite ...
.它发生在其他操作而不是
opposite
, 任何这样的组合就是它自己的身份,比如 reverse
.是否可以使用仿函数/单子(monad)/应用程序/箭头来克服这种情况? (我不太了解这些概念)。我想要的是能够定义一个属性或组合模式,如下所示:
opposite . opposite = id -- or, opposite (opposite y) = y
为了使编译器或解释器避免计算对立面的对立面(在某些连接语言中可能且简单( native ))。
最佳答案
你可以在没有任何单子(monad)的情况下解决这个问题,因为逻辑非常简单:
f g h = go False where
go _ [] = []
go b (x':xs)
| x >= 0 = g x : go b xs
| otherwise = h x : go (not b) xs
where x = (if b then negate else id) x'
go
的正文功能几乎与您原来的 f
相同功能。唯一的区别是 go
根据从先前调用传递给它的 bool 值决定是否应该对元素取反。
关于haskell - 是否可以在函数或仿函数中定义组合模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33313556/