Skip to content

Instantly share code, notes, and snippets.

@bixuanzju
Last active November 10, 2017 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bixuanzju/4f8ff1b2a83eb7151d4ef9aa33c697d7 to your computer and use it in GitHub Desktop.
Save bixuanzju/4f8ff1b2a83eb7151d4ef9aa33c697d7 to your computer and use it in GitHub Desktop.
church-encoding
{-# 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