How to find node path in Haskell Data.Tree

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?

+4
source share
2 answers

Traversable Foldable , (, State). , , - node node.

, :

pathsToNode :: Eq a => a -> Tree a -> [[a]]
pathsToNode x (Node y ns) = [[x] | x == y] ++ map (y:) (pathsToNode x =<< ns)

x, , , .

+5

, catamorphism. , "" , "" , . , .

cata Data.Functor.Foldable ( Data.Foldable! ) recursion-schemes. , Data.Tree , , :

{-# LANGUAGE DeriveFunctor #-}

import Data.Functor.Foldable

data Node a b = Node a [b] deriving (Functor,Eq)

type Tree a = Fix (Node a)

tree :: Tree Int
tree = Fix (Node 1 [ Fix ( Node 2 [ Fix (Node 3 []) ]), 
                     Fix ( Node 4 [] ) ])

cata, . :

paths :: Tree a -> [(a,[a])]
paths = cata algebra  
    where
    algebra :: Node a [(a,[a])] -> [(a,[a])]
    algebra (Node a as) = (a,[a]) : map (\(i,is)->(i,a:is)) (concat as) 

pathToNode:

pathToNode :: (Eq a) => a -> Tree a -> [a]
pathToNode a = snd . head . filter ((==a).fst) . paths 

, , - .

+5

Source: https://habr.com/ru/post/1524017/


All Articles