I can't quite figure out this syntax problem with a case
expression in a do
block.
What is the correct syntax?
If you could correct my example and explain it that would be the best.
module Main where main = do putStrLn "This is a test" s <- foo putStrLn s foo = do args <- getArgs return case args of [] -> "No Args" [s]-> "Some Args"
A little update. My source file was a mix of spaces and tabs and it was causing all kinds of problems. Just a tip for any one else starting in Haskell. If you are having problems check for tabs and spaces in your source code.
The case expression in Haskell Many imperative languages have Switch case syntax: we take a variable and execute blocks of code for specific values of that variable. We might also include a catch-all block of code in case the variable has some value for which we didn't set up a case.
It represents "computations that could fail to return a value". Just like with the fmap example, this lets you do a whole bunch of computations without having to explicitly check for errors after each step.
It's not equivalent to _ , it's equivalent to any other identifier. That is if an identifier is used as a pattern in Haskell, the pattern always matches and the matched value is bound to that identifier (unlike _ where it also always matches, but the matched value is discarded).
return is an (overloaded) function, and it's not expecting its first argument to be a keyword. You can either parenthesize:
module Main where import System(getArgs) main = do putStrLn "This is a test" s <- foo putStrLn s foo = do args <- getArgs return (case args of [] -> "No Args" [s]-> "Some Args")
or use the handy application operator ($):
foo = do args <- getArgs return $ case args of [] -> "No Args" [s]-> "Some Args"
Stylewise, I'd break it out into another function:
foo = do args <- getArgs return (has_args args) has_args [] = "No Args" has_args _ = "Some Args"
but you still need to parenthesize or use ($), because return takes one argument, and function application is the highest precedence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With