Last active
November 9, 2018 04:51
-
-
Save bruno-cadorette/5ea827c8b0677a6e63adbf60688e1ca8 to your computer and use it in GitHub Desktop.
binary tree insertion using paramorphism
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 TypeFamilies, DeriveFunctor #-} | |
| import Data.Functor.Foldable | |
| data Tree a = Leaf | Node a (Tree a) (Tree a) deriving (Show) | |
| data TreeF a b = LeafF | NodeF a b b deriving (Functor, Show) | |
| type instance Base (Tree a) = TreeF a | |
| instance Recursive (Tree a) where | |
| project Leaf = LeafF | |
| project (Node a b c) = NodeF a b c | |
| search = fst | |
| stay = snd | |
| insertAlgebra a LeafF = Node a Leaf Leaf | |
| insertAlgebra a (NodeF b left right) | |
| | a < b = Node b (search left) (stay right) -- only search in the left, the right side of the tree is untouched | |
| | a > b = Node b (stay left) (search right) -- only search in the right, the left side of the tree is untouched | |
| | otherwise = Node b (stay left) (stay right) -- stop the recursion | |
| insert x = para (insertAlgebra x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment