enr*_*que 4 haskell composition
考虑以下情况.我定义了一个函数来处理元素列表,通过在头上执行操作的典型方法并在列表的其余部分上调用函数.但在元素的某些条件下(为负面,是一个特殊字符,......)我会在继续之前更改列表其余部分的符号.像这样:
f [] = []
f (x : xs)
| x >= 0 = g x : f xs
| otherwise = h x : f (opposite xs)
opposite [] = []
opposite (y : ys) = negate y : opposite ys
Run Code Online (Sandbox Code Playgroud)
因为opposite (opposite xs) = xs,我变成了多余的相反操作的情况,积累opposite . opposite . opposite ....
它发生在其他操作而不是opposite任何这样的组合物本身就是身份,就像reverse.
是否有可能使用仿函数/ monads/applicatives /箭头克服这种情况?(我不太了解这些概念).我想要的是能够定义属性或组合模式,如下所示:
opposite . opposite = id -- or, opposite (opposite y) = y
Run Code Online (Sandbox Code Playgroud)
为了使编译器或解释器避免计算相反的相反(在一些连接语言中它是可能的和简单的(本机的)).
当然,只需保持一点状态告诉是否应用于negate当前元素.从而:
f = mapM $ \x_ -> do
x <- gets (\b -> if b then x_ else negate x_)
if x >= 0
then return (g x)
else modify not >> return (h x)
Run Code Online (Sandbox Code Playgroud)
你可以在没有任何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'
Run Code Online (Sandbox Code Playgroud)
go函数的主体几乎与原始f函数的主体相同.唯一的区别是go根据先前调用传递给它的布尔值来决定元素是否应该被否定.