我可以避免“向右漂移”在Haskell? [英] Can I avoid "rightward drift" in Haskell?
问题描述
当我使用命令式语言时,我经常写下像
When I use an imperative language I often write code like
foo (x) {
if (x < 0) return True;
y = getForX(x);
if (y < 0) return True;
return x < y;
}
也就是说,我逐条检查条件,尽可能快
。
That is, I check conditions off one by one, breaking out of the block as soon as possible.
我喜欢这个,因为它保持代码flat,并遵守end
weight的原则。我认为它更易读。
I like this because it keeps the code "flat" and obeys the principle of "end weight". I consider it to be more readable.
但是在Haskell我会写成
But in Haskell I would have written that as
foo x = do
if x < 0
then return x
else do
y <- getForX x
if y < 0
then return True
else return $ x < y
我不喜欢那么多。我可以使用允许分解的monad,但
,因为我已经使用monad我必须提升
一切,它添加词
我想避免,如果我可以。
Which I don't like as much. I could use a monad that allows breaking out, but
since I'm already using a monad I'd have to lift
everything, which adds words
I'd like to avoid if I can.
我想没有真正完美的解决方案,但任何人都有
任何建议吗?
I suppose there's not really a perfect solution to this but does anyone have any advice?
推荐答案
对于你的具体问题:如何dangling do
符号和逻辑?
For your specific question: How about dangling do
notation and the usage of logic?
foo x = do
if x < 0 then return x else do
y <- getForX x
return $ y < 0 || x < y
编辑
说,你甚至可以得到更漂亮的代码:
Edit
Combined with what hammar said, you can even get more beautiful code:
foo x | x < 0 = return x
| otherwise = do y <- getForX x
return $ y < 0 || x < y
这篇关于我可以避免“向右漂移”在Haskell?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!