Haskell, lesson 5
Haskell has no for or while statement. Since names can't change, a counter that goes up
by one each pass doesn't make sense. Instead you describe what to repeat over, usually a
list, and let functions do the repeating. It feels strange for a day or two, then it feels
natural.
A range builds a list of numbers:
mapM_ takes an action-making function and a list, and runs the action once per item, in
order. It's the closest thing to a for loop:
When the action needs more than one step, use a lambda (an unnamed function, written with a backslash):
Control.Monad also provides forM_, which is the same thing with the arguments swapped,
so the list comes first. Some people find that reads more like a loop.
2 exercises to try what you just read.
The fundamental way to repeat in Haskell is recursion: a function that calls itself on a smaller problem, plus a base case that stops it.
x : xs puts x in front of the list xs. So countdown 2 is "2" : countdown 1, which is
"2" : "1" : ["Go!"], which is ["2","1","Go!"]. The pattern 0 is the base case; without
it the function would never stop.
Recursion works for IO too. This action keeps reading lines until it sees end:
getContents gives you the whole of stdin as one string, and lines splits it into a list
of lines. Haskell reads it lazily, so this is fine even for large inputs:
To stop at a marker, you don't break out of anything. You just keep the part of the list
before it. takeWhile keeps items while a test is true and drops everything from the
first failure onward:
(/= 0) is a section: an operator with one side filled in, which makes a function that
asks "is this not zero?". Thanks to laziness, Haskell won't even parse the lines after the
marker.
Read a whole number n (0 or more). Print the numbers from n down to 1, one per line, and
then Liftoff!.
Sample input:
Sample output:
Your fitness tracker sends one whole number per line: the steps walked each day. A line
containing 0 marks the end of the data, and anything after it must be ignored. Print how
many days came before the 0, and their total:
Sample input:
Sample output:
Hint: getContents, lines, map read, takeWhile, length and sum are all you need.
[1 .. 5] -- [1,2,3,4,5]
[0, 5 .. 20] -- [0,5,10,15,20] (the second item sets the step)
[3, 2 .. 1] -- [3,2,1] (counting down)
[1 .. 0] -- [] (empty)main :: IO ()
main = mapM_ print [1 .. 3]
-- 1
-- 2
-- 3main :: IO ()
main = mapM_ (\i -> putStrLn ("Lap " ++ show i)) [1 .. 3]countdown :: Int -> [String]
countdown 0 = ["Go!"]
countdown n = show n : countdown (n - 1)echo :: IO ()
echo = do
line <- getLine
if line == "end"
then putStrLn "Bye"
else do
putStrLn ("Got: " ++ line)
echomain :: IO ()
main = do
contents <- getContents
let numbers = map read (lines contents) :: [Int]
print (sum numbers)takeWhile (/= 0) [5, 3, 0, 8] -- [5,3]
takeWhile (< 10) [1, 4, 9, 16] -- [1,4,9]33
2
1
Liftoff!Days: <count>
Total: <sum>4000
6500
3000
0Days: 3
Total: 13500