Created
November 20, 2015 07:51
-
-
Save kuanyingchou/d04e3f1c40bdd9fd4eed to your computer and use it in GitHub Desktop.
This file contains 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
sum : Tree Int -> Int | |
sum tree = | |
case tree of | |
Empty -> 0 | |
Node v left right -> | |
v + sum left + sum right | |
flatten : Tree a -> List a | |
flatten tree = | |
case tree of | |
Empty -> [] | |
Node v left right -> flatten left ++ [v] ++ flatten right | |
isElement : a -> Tree a -> Bool | |
isElement e tree = | |
case tree of | |
Empty -> False | |
Node v left right -> | |
if e == v then | |
True | |
else | |
(isElement e left) || (isElement e right) | |
fold : (a -> b -> b) -> b -> Tree a -> b | |
fold f a tree = | |
case tree of | |
Empty -> a | |
Node v left right -> | |
fold f (fold f (f v a) left) right | |
sum' : Tree Int -> Int | |
sum' tree = fold (+) 0 tree | |
flatten' : Tree a -> List a | |
flatten' tree = fold (::) [] tree | |
isElement' : a -> Tree a -> Bool | |
isElement' t tree = | |
fold (\x y -> (x==t) || y) False tree | |
preorder : Tree a -> List a | |
preorder tree = | |
case tree of | |
Empty -> [] | |
Node v left right -> | |
[v] ++ preorder left ++ preorder right | |
inorder : Tree a -> List a | |
inorder tree = | |
case tree of | |
Empty -> [] | |
Node v left right -> | |
preorder left ++ [v] ++ preorder right | |
postorder : Tree a -> List a | |
postorder tree = | |
case tree of | |
Empty -> [] | |
Node v left right -> | |
preorder left ++ preorder right ++ [v] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I've started learning elm recently mostly by reading docs and going through examples.
When I am attempting to solve binary tree challenges here http://elm-lang.org/examples/binary-tree , I am getting some weird errors. I thought I was doing something wrong. But I am doing similar to your code here.
I am running into two issues
I am using Elm-make version 0.16 in my PC, running the code in my PC and on online editor gives me the same errors.
However if I use the code posted here https://gist.github.com/cskksc/3e3c40195b9ada88adb7 . I am able to run the code without any errors.
He is flattening the tree to a list and folding over the list instead of folding over the tree.
Is it the only way to do it? Can you provide me some insights into this why this is happening with our code?
Sorry for the long comment.
Thank you