Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created October 6, 2023 14:17
Show Gist options
  • Save jtpaasch/bcba1b5a3f3456c2de6bc3a11f35e60b to your computer and use it in GitHub Desktop.
Save jtpaasch/bcba1b5a3f3456c2de6bc3a11f35e60b to your computer and use it in GitHub Desktop.
The difference between fold left and fold right
-- This version of fold applies 'f' to the head of the list '[a]'
-- to get a new accumulation 'acc', then it recurses into the tail
-- of the list '[a]' where it then repeats. This means that the
-- accumulated results are built up by adding in the elements
-- of the list, one at a time, starting with the first element
-- (on the left), and then moving through them, going right.
foldLeft :: (b -> a -> b) -> b -> [a] -> b
foldLeft f acc xs =
case xs of
[] -> acc
hd : tl -> foldLeft f (f acc hd) tl -- add the 'hd' to the accumulated results, then proceed into 'tl'
-- This version of fold recurses into the tail 'tl' of the list '[a]'
-- first, before applying 'f' to 'hd'. So, when it applies 'f' to 'hd',
-- it is using the accumulated results that were already compiled for
-- the tail of the list. Of course, when it recurses into the tail,
-- it will repeat, and go to the tail of that tail, and then again,
-- go into the tail of that tail, etc, until it hits the last item
-- in the list (on the far right). Then it will apply 'f' to that last
-- item to get a new accumulation, and it will back out, one element
-- at a time, until it gets back to the first element (on the far left).
-- Hence, this folds over the elements starting on the right, and
-- then moving to left.
foldRight :: (a -> b -> b) -> b -> [a] -> b
foldRight f acc xs =
case xs of
[] -> acc
hd : tl -> f hd (foldRight f acc tl) -- go into 'tl' first, then add the returned accumulation to 'hd'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment