Skip to content

Instantly share code, notes, and snippets.

@jtobin
Created January 31, 2016 05:27
Show Gist options
  • Save jtobin/2117bc788c674c6f8266 to your computer and use it in GitHub Desktop.
Save jtobin/2117bc788c674c6f8266 to your computer and use it in GitHub Desktop.
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