Skip to content

Instantly share code, notes, and snippets.

@Garciat
Created November 16, 2015 19:02
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 Garciat/d5f47d2fcfa98830efe9 to your computer and use it in GitHub Desktop.
Save Garciat/d5f47d2fcfa98830efe9 to your computer and use it in GitHub Desktop.
{-# LANGUAGE RankNTypes #-}
import qualified Prelude
import Prelude (Show(..), Functor(..), ($), (++), Monoid(..))
------------------
data Bool
= False
| True
newtype BoolF = BoolF { bool :: forall a. a -> a -> a }
true, false :: BoolF
true = BoolF $ \x _ -> x
false = BoolF $ \_ x -> x
or, and :: BoolF -> BoolF -> BoolF
p `or` q = BoolF $ \x y -> bool p x (bool q x y)
p `and` q = BoolF $ \x y -> bool p (bool q x y) y
instance Show BoolF where
show p = bool p "True" "False"
------------------
data List a
= Nil
| Cons a (List a)
newtype ListF a = ListF { list :: forall b. b -> (a -> ListF a -> b) -> b }
nil :: ListF a
nil = ListF $ \x _ -> x
cons :: a -> ListF a -> ListF a
cons x xs = ListF $ \_ f -> f x xs
foldl :: (a -> b -> b) -> b -> ListF a -> b
foldl f o xs = list xs o (\x xs -> x `f` foldl f o xs)
intercalate :: a -> ListF a -> ListF a
intercalate w xs = list xs nil (\x xs -> cons x (foldl (\x' xs' -> cons w (cons x' xs')) nil xs))
instance Monoid (ListF a) where
mempty = nil
mappend xs ys = list xs ys (\x xs -> cons x (mappend xs ys))
instance Functor ListF where
fmap f xs = list xs nil (\x xs -> cons (f x) (fmap f xs))
instance Show a => Show (ListF a) where
show xs = "[" ++ foldl (++) "" (intercalate "," $ fmap show xs) ++ "]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment