Created
November 23, 2013 05:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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