View Category

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
haskell
name = "Bob"
main = if name == "Bob" then putStrLn "Hello, Bob!" else return ()

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
haskell
putStrLn ("You are " ++ if age > 42 then "old" else "young")

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

haskell
f age
| age > 84 = putStrLn "You are really ancient"
| age > 30 = putStrLn "You are middle-aged"
| otherwise = putStrLn "You are young"

main = f age
where age = 31

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
haskell
suffixed n = show n ++ suffix
where
suffix
| n `mod` 100 `div` 10 == 1 = "th"
| otherwise = case n `mod` 10 of
1 -> "st"
2 -> "nd"
3 -> "rd"
_ -> "th"


result = map suffixed [1..40]

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
haskell
main :: IO ()
main = loop 1
where
loop x | x < 150 = do
putStr (show x ++ ",")
loop (x * 2)
loop _ = return ()
main = mapM_ print $ takeWhile (<150) $ iterate (* 2) 1

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
haskell
import System.Random

diceRolls = do
gen <- newStdGen
print $ takeWhile (/=(6::Int)) (randomRs (1,6) gen)

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
haskell
import Control.Monad

hi5 = replicateM_ 5 $ putStr "Hello"

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
haskell
countDown = mapM_ printN [10,9..1] >> putStr "Liftoff!"
where printN n = putStr $ show n ++ " .. "