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
mapM_ print stationsprints each pair, whilemapM_ (putStrLn . fst) stationsprints only the names.padlines the columns up by appendingreplicate (n - length s) ' '.forM_ stationstakes the list first, which lets the lambda body come last in the block.
Keywords and builtins used here
IOIntStringdoforM_importmainpadstations
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.
Step 3 of 3 in IO basics, step 24 of 27 in Language basics.