Skip to content

Instantly share code, notes, and snippets.

@jackwillis
Last active October 19, 2017 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackwillis/778b539bf66552a9f0a45b290e43ea85 to your computer and use it in GitHub Desktop.
Save jackwillis/778b539bf66552a9f0a45b290e43ea85 to your computer and use it in GitHub Desktop.
How to correctly write left fold in Haskell
{-# LANGUAGE NoMonomorphismRestriction #-}
-- pull in the necessary modules
import Control.Cond (if')
import Control.Monad (ap)
import Control.Monad.Fix (fix)
import Data.Foldable (null)
-- fold over a list
fold :: (a -> b -> a) -> a -> [b] -> a
fold = x ((a (a . f (i . n)) .) . f f t . ((f . (a .)) .) . (`a` (f f h . ((.) .))) . (((.) . (.)) .))
where a = ap; f = flip; h = head; i = if'; n = null; t = tail; x = fix
main = print $ fold (*) 1 [1..6] -- 720
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment