case expressions
editExercises |
---|
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, revisited
editExercises |
---|
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"
|
1.
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."
where
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.