qrest
qrest

Reputation: 3083

In haskell, combining "case" and ">>="

I have a lot of code of the style:

do
  x <- getSomething
  case x of
    this -> ...
    that -> ...
    other -> ...

Any way of me combining the "x <- ..." and "case x of" lines to eliminate the need for a variable?

Upvotes: 7

Views: 362

Answers (3)

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

If you want something extremely close to:

getSomething >>= caseOf
    this  -> expr1
    that  -> expr2
    other -> expr3

Then I think you're just out of luck - there is no such syntax in Haskell. But know you are not alone. Mark Jones defined the Habit language to include a sort of monadic case with the syntax:

case<- getSomething of
    Nothing -> expr1
    Just x  -> expr2 x

He refers to this as a "Case-From" statement in the language definition.

Upvotes: 0

Anthony
Anthony

Reputation: 3791

I do this as

foo "this" = return 2
foo "that" = return 3

main = foo =<< getSomething

The nice thing about this approach is that if foo is pure then this becomes

main = foo <$> getSomething

So the code retains the same shape for somewhat varying circumstances.

Upvotes: 0

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179109

You could use the bind operator >>= to pipe the x.

import System.Environment (getArgs)

main :: IO ()
main = getArgs >>= process
    where process ["xxx"] = putStrLn "You entered xxx"
          process ["yyy"] = putStrLn "You entered yyy"
          process _       = putStrLn "Error"

Upvotes: 6

Related Questions