Skip to content

Instantly share code, notes, and snippets.

@jtobin jtobin/foo.hs
Created Jan 31, 2016

Embed
What would you like to do?
Using recursion-schemes w/non-functor type
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeFamilies #-}
import Data.Functor.Foldable hiding (Foldable, Unfoldable)
import qualified Data.Functor.Foldable as RS (Foldable, Unfoldable)
data Expr =
Num Int
| Sum Expr Expr
deriving (Eq, Show)
data ExprF r =
NumF Int
| SumF r r
deriving Functor
type instance Base Expr = ExprF
instance RS.Foldable Expr where
project (Num j) = NumF j
project (Sum e0 e1) = SumF e0 e1
instance RS.Unfoldable Expr where
embed (NumF j) = Num j
embed (SumF e0 e1) = Sum e0 e1
eval :: Expr -> Int
eval = cata $ \case
NumF j -> j
SumF e0 e1 -> e0 + e1
test :: Expr
test = Sum (Num 1) (Num 2)
main :: IO ()
main = print $ eval test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.