Skip to content

Instantly share code, notes, and snippets.

@cheecheeo
Created November 26, 2013 03:37
Show Gist options
  • Save cheecheeo/7653116 to your computer and use it in GitHub Desktop.
Save cheecheeo/7653116 to your computer and use it in GitHub Desktop.
Somebody said that lists are the "free monoid" in Haskell
module MonoidFun where
-----------------------------------------------------------------------------
-- |
-- Inspirition from: http://stackoverflow.com/a/13357359/1019205 lists are
-- the "free monoid" and http://hackage.haskell.org/package/newtype
import Data.Monoid
import Data.Foldable
import Control.Newtype
-- | "fold" elements under an arbitrary 'Monoid'
-- >>> foldAsA Product [1..5]
-- 120
-- >>> foldAsA Sum [1..5]
-- 15
foldAsA :: (Foldable t, Monoid n', Newtype n' o) => (o -> n') -> t o -> o
foldAsA = flip ala foldMap
-- | A synonym for 'foldAsA' for Grammarians
-- >>> foldAsAn All [True, False, True]
-- False
-- >>> foldAsAn Any []
-- False
foldAsAn :: (Foldable t, Monoid n', Newtype n' o) => (o -> n') -> t o -> o
foldAsAn = foldAsA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment