Haskell/Solutions/Control structures

← Back to Control structures

case expressionsEdit

Use a case statement to implement a fakeIf function which might be used as a replacement to the familiar if expressions.

fakeIf :: Bool -> a -> a -> a
fakeIf condition ifTrue ifFalse =
  case condition of
    True  -> ifTrue
    False -> ifFalse

Controlling actions, revisitedEdit

  1. Redo the "Haskell greeting" exercise in Simple input and output/Controlling actions, this time using a case statement.
  2. What does the following program print out? And why?
main =
 do x <- getX
    putStrLn x

getX =
 do return "My Shangri-La"
    return "beneath"
    return "the summer moon"
    return "I will"
    return "return"
    return "again"


main = do
  putStrLn "Hello, what is your name?"
  name <- getLine
  case name of
      "Simon" -> greatlanguage
      "John"  -> greatlanguage
      "Phil"  -> greatlanguage
      "Koen"  -> putStrLn "I think debugging Haskell is fun."
      _       -> putStrLn "Sorry, I don't know you."
      greatlanguage = putStrLn "I think Haskell is a great programming language."

2. Executing main will print "again". Remember that the value of a sequence of IO actions is the same as the value of the last action in the sequence. getX can also be written as:

getX =
  do return "again"

or even shorter, as:

getX = return "again"

As a result, x in the main function has the value "again", which will then be written to the screen.