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?
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?
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"
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.
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.