Learn/Haskell/5. Repetition without loops
Lesson 5 of 8
Sign in

Haskell, lesson 5

Repetition without loops

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.

Ranges

A range builds a list of numbers:

Doing an action for every item: mapM_

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.

Exercise 1

Countdown

Press Ctrl Enter or Check to test your code.

Exercise 2

Step counter

Press Ctrl Enter or Check to test your code.

Recursion

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:

Reading all input at once

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:

Stopping early: takeWhile

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.

Further reading

  • A Gentle Introduction to Haskell: Functions (sections, lambdas)
  • Haskell 2010 Report: Arithmetic sequences
  • Prelude: mapM_, takeWhile, getContents

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
-- 3
main :: 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)
      echo
main :: 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]
3
3
2
1
Liftoff!
Days: <count>
Total: <sum>
4000
6500
3000
0
Days: 3
Total: 13500