Last active
November 10, 2017 05:30
-
-
Save bixuanzju/4f8ff1b2a83eb7151d4ef9aa33c697d7 to your computer and use it in GitHub Desktop.
church-encoding
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 RankNTypes #-} | |
newtype BST k v = Roll | |
{ unroll :: forall r. r -> (k -> v -> r -> r -> r) -> r | |
} | |
-- Two constructors | |
leave :: BST k v | |
leave = Roll const | |
node :: Ord k => k -> v -> BST k v -> BST k v -> BST k v | |
node k v l r = Roll $ \ d b -> b k v (unroll l d b) (unroll r d b) | |
lookup' :: Ord k => k -> BST k v -> Maybe v | |
lookup' k bst = unroll bst Nothing $ \k' v l r -> | |
case compare k k' of | |
EQ -> Just v | |
LT -> l | |
GT -> r | |
insert :: Ord k => k -> v -> BST k v -> BST k v | |
insert k v bst = unroll bst (node k v leave leave) $ \k' v' l r -> | |
case compare k k' of | |
GT -> node k' v' l (insert k v r) | |
_ -> node k' v' (insert k v l) r | |
main :: IO () | |
main = do | |
let tree = insert 1 'c' (insert 2 'b' leave) | |
let res = lookup' 2 tree | |
print res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment