typestar

Printing with mapM_ in Haskell

mapM_ runs an action per element and drops the results; forM_ is the same with flipped arguments.

import Control.Monad (forM_)

stations :: [(String, Int)]
stations = [("north", 4), ("central", 11), ("south", 7)]

-- Pad on the right so the columns line up.
pad :: Int -> String -> String
pad n s = s ++ replicate (n - length s) ' '

main :: IO ()
main = do
  -- mapM_ runs an action per element and discards the results.
  mapM_ print stations
  mapM_ (putStrLn . fst) stations
  -- forM_ is mapM_ with the arguments flipped, so the body comes last.
  forM_ stations $ \(name, bikes) ->
    putStrLn (pad 9 name ++ show bikes ++ " bikes free")

How it works

  1. mapM_ print stations prints each pair, while mapM_ (putStrLn . fst) stations prints only the names.
  2. pad lines the columns up by appending replicate (n - length s) ' '.
  3. forM_ stations takes the list first, which lets the lambda body come last in the block.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
532
Tokens
105
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 3 of 3 in IO basics, step 24 of 27 in Language basics.

← Previous Next →