01 02 03 04 05 06 01 02 03 04 05 06 07 08 09 10 11 12 13 14 ← →
module Main where
We can replace the repeated calls to addline
with a single operation, by
using a fold. One can fold from either the left or the right, combining an
initial value of type a
with a list of values of type b
, to produce a result
of type a
. The function foldl
folds from the left; foldr
folds from the
right.
foldl ∷ (a → b → a) → a → [b] → a foldr ∷ (b → a → a) → a → [b] → a
We are combining from the left, so we use foldl
.
hello ∷ String hello = foldl addline [] [first, second, third] where addline s t = s ++ t ++ "\n" first = "hello" second = "there" third = "world" main ∷ IO () main = putStr hello
hello there world