Haskell n-ary tree traversal

前端 未结 3 1615
一向
一向 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:08

    You're on the right lines with map, but after traversing each subtree you want to concat the resulting lists together. There's also no point breaking off the first element of the list with the (x:xs) pattern when using map. I'd write this as:

    travTree (Branch xs) = concatMap travTree xs
    

    (But beware; I haven't tested that! However I often find my "infinite type a = [a]" problems are caused by a map where concatMap is needed.)

提交回复
热议问题