Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell syntax for a case expression in a do block

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.

like image 724
Ted Avatar asked Oct 01 '08 02:10

Ted


People also ask

What is a case expression in Haskell?

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.

What does Just do in Haskell?

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.

What is otherwise in Haskell?

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).


1 Answers

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.

like image 177
wnoise Avatar answered Sep 22 '22 16:09

wnoise