Created
February 4, 2014 03:17
-
-
Save jonschoning/8797627 to your computer and use it in GitHub Desktop.
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 DeriveFunctor #-} | |
data ExprF r = Const Int | |
| Add r r | |
| Mul r r | |
deriving Functor | |
newtype Fix f = Fx (f (Fix f)) | |
unFix :: Fix f -> f (Fix f) | |
unFix (Fx x) = x | |
cata :: Functor f => (f a -> a) -> Fix f -> a | |
cata alg = alg . fmap (cata alg) . unFix | |
alg :: ExprF Int -> Int | |
alg (Const i) = i | |
alg (x `Add` y) = x + y | |
alg (x `Mul` y) = x * y | |
eval :: Fix ExprF -> Int | |
eval = cata alg | |
testExpr = Fx $ | |
(Fx $ (Fx $ Const 2) `Add` (Fx $ Const 3)) `Mul` | |
(Fx $ Const 4) | |
main = print $ eval $ testExpr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment