Skip to content

Instantly share code, notes, and snippets.

@bosu
Created June 3, 2014 14:34
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 bosu/4fdf685091ea7e0cb26f to your computer and use it in GitHub Desktop.
Save bosu/4fdf685091ea7e0cb26f to your computer and use it in GitHub Desktop.
Free Alternative
{-# LANGUAGE DeriveFunctor, FlexibleInstances #-}
{-# OPTIONS -Wall #-}
import Control.Monad.Free
import Control.Applicative
data SomeF f a = Many [a] | One (f a) deriving Functor
instance Functor f => Alternative (Free (SomeF f)) where
empty = Free (Many [])
(Free (Many [])) <|> a = a
a <|> (Free (Many [])) = a
(Free (Many as)) <|> (Free (Many bs)) = Free $ Many $ as ++ bs
a <|> (Free (Many bs)) = Free $ Many $ a : bs
(Free (Many as)) <|> b = Free $ Many $ as ++ [b]
a <|> b = Free $ Many [a, b]
liftFA :: Functor f => f a -> Free (SomeF f) a
liftFA = liftF . One
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment