Last active
October 30, 2020 08:38
-
-
Save cblp/3e8e1af031e6f6449c9c2fbf8736e8b2 to your computer and use it in GitHub Desktop.
Final Tagless Tree
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 FlexibleInstances #-} | |
{-# LANGUAGE GADTSyntax #-} | |
-- * (G)ADT | |
data DTree where | |
Empty :: DTree | |
Node :: String -> DTree -> DTree -> DTree | |
deriving (Show) | |
-- $> Node "bar" Empty $ Node "foo" Empty Empty | |
-- * Final Tagless | |
class FTTree tree where | |
empty :: tree | |
node :: String -> tree -> tree -> tree | |
ctree :: FTTree tree => tree | |
ctree = node "bar" empty $ node "foo" empty empty | |
-- * Interpratation as ADT | |
instance FTTree DTree where | |
empty = Empty | |
node = Node | |
-- $> ctree @DTree | |
-- * Interpratation as String | |
instance FTTree String where | |
empty = "empty" | |
node value left right = unwords ["(node", show value, left, right, ")"] | |
-- $> ctree @String | |
-- * Interpratation as IO | |
instance FTTree (IO ()) where | |
empty = putStr "empty" | |
node value left right = do | |
putStr "(node " | |
putStr $ show value | |
putStr " " | |
left | |
putStr " " | |
right | |
putStr ")" | |
-- $> ctree @(IO ()) >> putStrLn "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment