Skip to content

Instantly share code, notes, and snippets.

@nponeccop
Created August 16, 2015 01:22
Show Gist options
  • Save nponeccop/fd69e6738e6d1b264719 to your computer and use it in GitHub Desktop.
Save nponeccop/fd69e6738e6d1b264719 to your computer and use it in GitHub Desktop.
Unfolds, coalgebras and anamorphisms
{-# LANGUAGE DeriveFunctor #-}
import Data.Functor.Foldable
import Data.Function
unfold1 :: Unfold Int [Int]
unfold1 = xana coalgebra1
xana :: Unfoldable b => Coalgebra a b -> Unfold a b
xana = ana
type Coalgebra a b = a -> Base b a
type Unfold a b = a -> b
coalgebra1 :: Coalgebra Int [Int]
coalgebra1 5 = Nil
coalgebra1 x = Cons x (x + 1)
main = print "ho"
unfold2 :: Unfold Int [Int]
unfold2 5 = []
unfold2 x = x : unfold2 (x + 1)
unfold3 :: Unfold Int [Int]
unfold3 = fix f where
f _ 5 = []
f self x = x : self (x + 1)
unfold4 = fix f' where
f' self x = coalgebra x where
nil = []
cons a b = a : self b
coalgebra 5 = nil
coalgebra x = cons x (x + 1)
unfold3'' :: Unfold Int [Int]
unfold3'' = fix f' where
f' self x = foo' $ coalgebra1 x where
foo' = embed . fmap self
foo Nil = []
foo (Cons a b) = a : self b
type OurList a = Fix (OurBase a)
data OurBase a b = OurCons a b | OurNil deriving (Functor)
coalgebra2 :: Coalgebra Int (OurList Int)
coalgebra2 5 = OurNil
coalgebra2 x = OurCons x (x + 1)
coalgebra3 :: Coalgebra (OurList a) [a]
coalgebra3 (Fix OurNil) = Nil
coalgebra3 (Fix (OurCons a b)) = Cons a b
toList1 :: OurList a -> [a]
toList1 = cata algebra where
algebra OurNil = []
algebra (OurCons a b) = a : b
toList2 :: OurList a -> [a]
toList2 = ana coalgebra3
unfold5 :: Unfold Int (OurList Int)
unfold5 = ana coalgebra2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment