Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Multiple Case Statements in Single Function

I want to include more than one case statement in a Haskell function (see below for an example of a hypothetical function).

However, it is not legal Haskell. What is a better way of accomplishing the same thing? Furthermore, if the case statements are not returning anything, but simply setting some value, why is it not legal to have more than one case statement in a function?

(I would get a "parse error on input `case'" on line 5)

tester x y =  
   case (x < 0) of  
       True -> "less than zero."  
       False -> "greater than or equal to zero."  
   case (y == "foo")  
       True -> "the name is foo."  
       False -> "the name is not foo." 

Note that if my function were simply:

tester x y =  
   case (x < 0) of  
       True -> "less than zero."  
       False -> "greater than or equal to zero."

...then it would compile.

like image 742
well actually Avatar asked Nov 22 '10 03:11

well actually


1 Answers

In general the body of a function has to be a single expression (very often made up of smaller expressions). The following isn't allowed, for example:

f x y =
  "foo"
  "bar"

This is equivalent to your first example—we've just substituted one kind of expression (string literals) for another (your case expressions).

It's certainly possible to include more than one case expression in a Haskell function:

tester :: Int -> String -> (String, String)
tester x y = (a, b)
  where
    a = case (x < 0) of  
          True -> "less than zero."  
          False -> "greater than or equal to zero."  
    b = case (y == "foo") of
          True -> "the name is foo."  
          False -> "the name is not foo."

Or even:

tester :: Int -> String -> IO ()
tester x y = do
  putStrLn $ case (x < 0) of  
               True -> "less than zero."  
               False -> "greater than or equal to zero."  
  putStrLn $ case (y == "foo") of
               True -> "the name is foo."  
               False -> "the name is not foo."

These work because the body of the function is a single expression (although neither is really idiomatic Haskell).

like image 129
Travis Brown Avatar answered Sep 19 '22 17:09

Travis Brown