Skip to content

Instantly share code, notes, and snippets.

@manonthemat
Created August 6, 2021 01:42
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 manonthemat/760231aa537b83f068703a23deb2ed5d to your computer and use it in GitHub Desktop.
Save manonthemat/760231aa537b83f068703a23deb2ed5d to your computer and use it in GitHub Desktop.
Functional Programming in Haskell - The University of Glasgow
data Tree =
Leaf
| Node Int Tree Tree
deriving Show
treeDepth :: Tree -> Int
treeDepth Leaf = 0
treeDepth (Node _ a b) = 1 + max (treeDepth a) (treeDepth b)
treeSum :: Tree -> Int
treeSum Leaf = 0
treeSum (Node n a b) = n + treeSum a + treeSum b
isSortedTree :: Tree -> Int -> Int -> Bool
isSortedTree Leaf _ _ = True
isSortedTree (Node x leftSubtree rightSubtree) minVal maxVal =
let leftSorted = isSortedTree leftSubtree minVal x
rightSorted = isSortedTree rightSubtree x maxVal
in x >= minVal && x < maxVal && leftSorted && rightSorted
-- isSortedTree (Node 2 (Node 1 Leaf Leaf) (Node 3 Leaf Leaf)) minBound maxBound
addNewMax :: Tree -> Tree
addNewMax Leaf = Node 0 Leaf Leaf
addNewMax (Node x t1 Leaf) = Node x t1 (Node (x+1) Leaf Leaf)
addNewMax (Node x t1 t2) = Node x t1 (addNewMax t2)
treeToList :: Tree -> [Int]
treeToList Leaf = []
treeToList (Node value leftSubtree rightSubtree) =
mconcat [treeToList leftSubtree, [value], treeToList rightSubtree]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment