2

I am trying to replicate the following requirements/code in Haskell

Pseudo-Code (the actual evaluations are much more complicated):

if (x == 1)
   doX()
else if (y == 1)
   doY()
else if (z == 1)
   doZ()
else
   doSomethingElse()

Right now I have this as WHEN statements for each, but that doesn't give me an ELSE, so I have

when (x == 1) $ do doX
when (y == 1) $ do doY
when (z == 1) $ do doZ

But then how do I manage my else?

3
  • 1
    Although @bheklilr's guards are more idiomatic for this, Haskell does have if ... then ... else ... expressions, so the pseudocode is only missing thens to be legal Haskell. (But watch out for indentation if using if then else together with do.) Commented Aug 3, 2014 at 3:48
  • @ØrjanJohansen This is pretty much the reason why I chose guards for my examples, they avoid the nastiness of having to worry about indentation. Commented Aug 3, 2014 at 3:52
  • Not a serious answer: [doX, doY, doZ] !! findIndex (==1) [x, y, z] Commented Aug 3, 2014 at 7:27

1 Answer 1

5

This looks like a good option for guards or a case statement. You could do something like

myAction :: Monad m => Int -> Int -> Int -> m ()
myAction x y z
    | x == 1 = doX
    | y == 1 = doY
    | z == 1 = doZ
    | otherwise = doSomethingElse

Or you can use the MultiWayIf extension:

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
Sign up to request clarification or add additional context in comments.

1 Comment

You can even fake a multiway if with case () of () | p1 -> e1; () | p2 -> e2 ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.