Created
January 31, 2016 05:27
-
-
Save jtobin/2117bc788c674c6f8266 to your computer and use it in GitHub Desktop.
Using recursion-schemes w/non-functor type
This file contains hidden or 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 #-} | |
{-# 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