Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Last active October 5, 2019 23:47
Show Gist options
  • Save pedrominicz/0f970a174c6f713b13b7b2a3b7a1e1fa to your computer and use it in GitHub Desktop.
Save pedrominicz/0f970a174c6f713b13b7b2a3b7a1e1fa to your computer and use it in GitHub Desktop.
Haskell doodle (F-Algebras, very short)
module FAlgebra where
-- https://www.schoolofhaskell.com/user/bartosz/understanding-algebras
{-
class Functor f where
fmap :: (a -> b) -> f a -> f b
(<$) :: a -> f b -> f a
(<$) = fmap . const
{-# MINIMAL fmap #-}
-}
type Algebra f a = f a -> a
data ExprF a
= Const Integer
| Add a a
| Mul a a
-- fix :: a -> [a]
-- fix x = x : fix x
--
-- fix :: (a -> a) -> a
-- fix f = let x = f x in x
newtype Fix f = Fix (f (Fix f))
type Expr = Fix ExprF
expr :: Expr
expr = Fix $ (Fix $ Const 2) `Add` (Fix $ Const 3)
instance Functor ExprF where
fmap _ (Const x) = Const x
fmap eval (x `Add` y) = (eval x) `Add` (eval y)
fmap eval (x `Mul` y) = (eval x) `Mul` (eval y)
type ExprAlgebra = Algebra ExprF (Fix ExprF)
algebra :: ExprAlgebra
algebra = Fix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment