Created
February 25, 2016 04:44
-
-
Save sirlensalot/c0dd68f673be4cdc5152 to your computer and use it in GitHub Desktop.
Tree is a comonad
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
λ> import Data.Tree | |
λ> import Control.Comonad | |
λ> let t = Node (1::Int) [Node 2 [Node 4 [],Node 5 []],Node 3 [Node 6 [],Node 7 []]] | |
λ> let draw = putStrLn . drawTree . fmap show | |
λ> draw t | |
1 | |
| | |
+- 2 | |
| | | |
| +- 4 | |
| | | |
| `- 5 | |
| | |
`- 3 | |
| | |
+- 6 | |
| | |
`- 7 | |
λ> levels t | |
[[1],[2,3],[4,5,6,7]] | |
λ> draw (duplicate t) -- Comonad duplicate | |
Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = [Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []}]},Node {rootLabel = 3, subForest = [Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []}]}]} | |
| | |
+- Node {rootLabel = 2, subForest = [Node {rootLabel = 4, subForest = []},Node {rootLabel = 5, subForest = []}]} | |
| | | |
| +- Node {rootLabel = 4, subForest = []} | |
| | | |
| `- Node {rootLabel = 5, subForest = []} | |
| | |
`- Node {rootLabel = 3, subForest = [Node {rootLabel = 6, subForest = []},Node {rootLabel = 7, subForest = []}]} | |
| | |
+- Node {rootLabel = 6, subForest = []} | |
| | |
`- Node {rootLabel = 7, subForest = []} | |
λ> :t extend -- extend f === fmap f . duplicate | |
extend :: Comonad w => (w a -> b) -> w a -> w b | |
λ> draw $ extend levels t | |
[[1],[2,3],[4,5,6,7]] | |
| | |
+- [[2],[4,5]] | |
| | | |
| +- [[4]] | |
| | | |
| `- [[5]] | |
| | |
`- [[3],[6,7]] | |
| | |
+- [[6]] | |
| | |
`- [[7]] | |
λ> draw $ extend flatten t | |
[1,2,4,5,3,6,7] | |
| | |
+- [2,4,5] | |
| | | |
| +- [4] | |
| | | |
| `- [5] | |
| | |
`- [3,6,7] | |
| | |
+- [6] | |
| | |
`- [7] | |
λ> draw $ extend (sum.flatten) t | |
28 | |
| | |
+- 11 | |
| | | |
| +- 4 | |
| | | |
| `- 5 | |
| | |
`- 16 | |
| | |
+- 6 | |
| | |
`- 7 | |
λ> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment