Last active
August 16, 2018 15:24
-
-
Save lagenorhynque/b9f5ea9efd28dfcc4b23539ae1fb065d to your computer and use it in GitHub Desktop.
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
| dev> (defrecord Tree [left right]) | |
| dev.Tree | |
| dev> (defn ->list [tree] | |
| (letfn [(rec [acc {:keys [left right] :as t}] | |
| (if (instance? Tree t) | |
| (if (instance? Tree left) | |
| (recur acc (->Tree (:left left) (->Tree (:right left) right))) | |
| (recur (cons left acc) right)) | |
| (cons t acc)))] | |
| (reverse (rec [] tree)))) | |
| #'dev/->list | |
| dev> (->list 3) | |
| (3) | |
| dev> (->list (->Tree 3 4)) | |
| (3 4) | |
| dev> (->list (->Tree (->Tree (->Tree 2 3) 4) 5)) | |
| (2 3 4 5) |
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
| > data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show | |
| data Tree a = Leaf a | Branch (Tree a) (Tree a) | |
| [Prelude] | |
| > :{ | |
| Prelude| toList :: Tree a -> [a] | |
| Prelude| toList = reverse . rec [] | |
| Prelude| where | |
| Prelude| rec acc (Leaf v) = v : acc | |
| Prelude| rec acc (Branch (Leaf v) right) = rec (v : acc) right | |
| Prelude| rec acc (Branch (Branch left right) right') = rec acc (Branch left (Branch right right')) | |
| Prelude| :} | |
| toList :: Tree a -> [a] | |
| [Prelude] | |
| > toList $ Leaf 3 | |
| [3] | |
| it :: Num a => [a] | |
| [Prelude] | |
| > toList $ Branch (Leaf 3) (Leaf 4) | |
| [3,4] | |
| it :: Num a => [a] | |
| [Prelude] | |
| > toList $ Branch (Branch (Branch (Leaf 2) (Leaf 3)) (Leaf 4)) (Leaf 5) | |
| [2,3,4,5] | |
| it :: Num a => [a] |
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
| dev> (defn ->list' [tree] | |
| (letfn [(rec [acc {{:keys [left right] | |
| :as left'} :left | |
| right' :right | |
| :as t}] | |
| (if left | |
| (recur acc (->Tree left (->Tree right right'))) | |
| (if left' | |
| (recur (cons left' acc) right') | |
| (cons t acc))))] | |
| (reverse (rec [] tree)))) | |
| #'dev/->list' | |
| dev> (->list' 3) | |
| (3) | |
| dev> (->list' (->Tree 3 4)) | |
| (3 4) | |
| dev> (->list' (->Tree (->Tree (->Tree 2 3) 4) 5)) | |
| (2 3 4 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment