Skip to content

Instantly share code, notes, and snippets.

@luqui
Created November 23, 2013 05:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luqui/7611127 to your computer and use it in GitHub Desktop.
Save luqui/7611127 to your computer and use it in GitHub Desktop.
A neat list-like monoid that supports extracting information from both ends, even with undefined values in the middle.
{-# LANGUAGE RankNTypes #-}
import Data.Foldable
import Data.Monoid
newtype M a = M { getM :: forall m. Monoid m => (a -> m) -> m }
instance Monoid (M a) where
mempty = M $ const mempty
x `mappend` y = M $ \f -> getM x f `mappend` getM y f
singleton :: a -> M a
singleton x = M ($ x)
fromList :: [a] -> M a
fromList = foldMap singleton
front :: M a -> Maybe a
front m = getFirst (getM m (First . Just))
back :: M a -> Maybe a
back m = getLast (getM m (Last . Just))
funOrder = fromList [1..] <> singleton 0
okay = front funOrder
cool = back funOrder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment