Given a tree in Haskell (represented Data.Tree), how can I find the path to node?
eg.
import Data.Tree
tree = Node 1 [Node 2 [Node 3 []], Node 4 []]
Which forms a tree that looks like this:
1
|
+- 2
| |
| `- 3
|
`- 4
How can I make a function pathToNodesuch that:
pathToNode 0 tree => []
pathToNode 1 tree => [1]
pathToNode 2 tree => [1, 2]
pathToNode 3 tree => [1, 2, 3]
pathToNode 4 tree => [1, 4]
In my specific case, any given value will be displayed only once in the tree, so a solution returning the path to the value is acceptable.
So far my best answer is this:
pathToNode :: (Eq a) => a -> Tree a -> [a]
pathToNode x (Node y ys) | x == y = [x]
| otherwise = case concatMap (pathToNode x) ys of
[] -> []
path -> y:path
Is there a more concise way to write this? Can I use Data.Foldableor Data.Traversableto avoid writing my own move logic?
source
share