Last active
October 16, 2017 14:37
-
-
Save Abhiroop/033f567260fee63d66032f41d20fdb95 to your computer and use it in GitHub Desktop.
Creating a balanced binary search tree type in Haskell
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 GADTs, DataKinds #-} | |
module BST where | |
data Nat = Zero | Succ Nat | |
data Tree n a where | |
Branch :: T n a -> Tree (Succ n) a | |
Leaf :: Tree Zero a | |
data T n a = NodeR (Tree n a) a (Tree (Succ n) a) -- right subtree has height + 1 | |
| NodeL (Tree (Succ n) a) a (Tree n a) -- left subtree has height + 1 | |
| Node (Tree n a) a (Tree n a) -- both subtrees are of equidistant height | |
--Example | |
t :: Tree (Succ Zero) Integer | |
t = Branch $ NodeR Leaf 3 (Branch (Node Leaf 4 Leaf)) | |
{- | |
3 | |
/ \ | |
. 4 | |
/ \ | |
. . | |
-} | |
{- Doesn't compile | |
an unbalanced tree like this | |
3 | |
/ \ | |
. 4 | |
/ \ | |
. 5 | |
/ \ | |
. . | |
Now, | |
x :: Tree (Succ Zero) Integer | |
x = Branch $ Node Leaf 5 Leaf | |
Neither of these compile | |
t2 :: Tree (Succ (Succ Zero)) Integer | |
t2 = Branch (NodeR Leaf 3 (Branch (Node Leaf 4 x))) | |
or | |
t2 :: Tree (Succ Zero) Integer | |
t2 = Branch (NodeR Leaf 3 (Branch (Node Leaf 4 x))) | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment