Haskell n-ary tree traversal

前端 未结 3 1617
一向
一向 2021-02-04 14:51

I\'m pretty new to Haskell and I\'m trying to work out how to traverse a n-ary tree. As output I\'m looking to get a list of Leaf values (as the branches have no value), so for

3条回答
  •  日久生厌
    2021-02-04 15:30

    Traversing a tree means traversing all subtrees and flattening the resulting lists into one.

    This translates to

    travTree (Branch branches) = concat $ map travTree branches
    

    Note that there are even more concise notations like branches >>= travTree or concatMap travTree branches for the right hand side of this definition, but I consider the above one to be the clearest.

    Edit: Reintroducing the list-comprehension version for the sake of completeness:

    travTree (Branch branches) = [ elem | br <- branches, elem <- travTree br ]
    

提交回复
热议问题