Skip to content

Instantly share code, notes, and snippets.

@sirlensalot
Created February 25, 2016 04:44
Show Gist options
  • Save sirlensalot/c0dd68f673be4cdc5152 to your computer and use it in GitHub Desktop.
Save sirlensalot/c0dd68f673be4cdc5152 to your computer and use it in GitHub Desktop.
Tree is a comonad
λ> 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