Real World Haskell - 第4章 Part5 How to think about loops (続き)

Real World HaskellHaskell を継続的に勉強中。


Chapter 4. Functional programming
Chapter 4. Functional programming

How to think about loops

  • for/while ループは Haskell には存在しないので別の方法で表現する必要がある
The left fold
foldl :: (a -> b -> a) -> a -> [b] -> a

foldl step zero (x:xs) = foldl step (step zero x) xs
foldl _    zero []     = zero
foldlSum xs = foldl step 0 xs
    where step acc x = acc + x
foldl (+) 0 (1:2:3:[])
          == foldl (+) (0 + 1)             (2:3:[])
          == foldl (+) ((0 + 1) + 2)       (3:[])
          == foldl (+) (((0 + 1) + 2) + 3) []
          ==           (((0 + 1) + 2) + 3)
niceSum :: [Integer] -> Integer
niceSum xs = foldl (+) 0 xs
  • foldl すると再帰を明示的に書かなくて良くなる
    • コードが短くなるし読み易くなる
Why use folds, maps, and filters?
  • Haskell では fold, map, filter などは標準的なので再帰で書くより読み易くなる