我正在尝试在Haskell中复制以下需求/代码
伪代码(实际评估要复杂得多):
if (x == 1)
doX()
else if (y == 1)
doY()
else if (z == 1)
doZ()
else
doSomethingElse()
现在我把它作为每个的WHEN语句,但是这并没有给我一个ELSE,所以我有
when (x == 1) $ do doX
when (y == 1) $ do doY
when (z == 1) $ do doZ
但是我如何管理我的其他人?
答案 0 :(得分:5)
对于警卫或案件陈述来说,这看起来是个不错的选择。你可以做点什么
myAction :: Monad m => Int -> Int -> Int -> m ()
myAction x y z
| x == 1 = doX
| y == 1 = doY
| z == 1 = doZ
| otherwise = doSomethingElse
或者您可以使用MultiWayIf
扩展程序:
myAction :: Monad m => m ()
myAction = do
x <- getX
y <- getY
z <- getZ
if | x == 1 -> doX
| y == 1 -> doY
| z == 1 -> doZ
| otherwise -> doSomethingElse
-- continue doing more stuff in myAction as needed