klequis / zz-haskell-notebook

Notes from learning Haskell
1 stars 0 forks source link

`foldl` & `foldr` #59

Open klequis opened 2 years ago

klequis commented 2 years ago

fold reminds me of reduce in JavaScript.

foldl & foldr take

Associtivity

Example foldl (-) 0 [1, 2]

foldl f z [1, 2] -- add the array

foldl (-) 0 [1, 2] -- use (-) for f, use 0 for z

((0 `f` 1) `f` 2) -- I left `f` in while thinking about it

((0 `-` 1) `-` 2) -- Written out with `-` as infix

so f is (-)

((0 - 1) - 2) -- written out as a math equation
(-1 - 2)      -- reduce it
-3            -- reduce it

Example foldr f z [...]

foldr (-) 0 [1, 2]

1 `-` (2 `-` 0)
1 - (2 - 0)
1 - 2
-1

Example foldr (-) 0 [1, 2, 3, 4, 5]

1 `-` (2 `-` (3 `-` (4 `-` (5 `-` 0))))
1 - (2 - (3 - (4 - (5 - 0))))
1 - (2 - (3 - (4 - 5)))
1 - (2 - (3 - (-1)))
1 - (2 - 4)
1 - -2
3