简体   繁体   English

玫瑰树解构器

[英]Rose tree deconstructor

If we have a rose tree definition as follows: 如果我们有玫瑰树定义如下:

data Rose a = a :> [Rose a]

then I know that :> is an infix constructor. 那么我知道:>是一个infix构造函数。 But how do you work with elements of such a tree? 但是,您如何处理这种树的元素? How can you traverse it to visit nodes or extract subtrees or elements? 如何遍历它以访问节点或提取子树或元素?

You can pattern match on the constructor like this (for example): 您可以像这样在构造函数上进行模式匹配(例如):

find :: (Eq a) => a -> Rose a -> Bool
find item (top :> rest)
  | item == top = True
  | otherwise = any (find item) rest

Addressing your second problem: Yes you can do this without any further knowledge of functors, but it would make sense to create a functor instance because it would make your datastructure more flexible. 解决您的第二个问题:是的,您可以在无需进一步了解函子的情况下执行此操作,但是创建函子实例是有意义的,因为它将使您的数据结构更加灵活。 But lets get down to business: A map which processes every node would look something like this: 但是让我们开始工作:处理每个节点的map看起来像这样:

myMap :: (a -> b) -> Rose a -> Rose b
myMap f (node :> rest) = f node :> map (myMap f) rest

This is pretty easy to add to the functor typeclass, because it does exactly what we want: 这很容易添加到仿函数类型类中,因为它确实可以实现我们想要的功能:

instance Functor Rose where
  fmap :: (a -> b) -> Rose a -> Rose b
  fmap = myMap
subtrees :: Rose a -> [Rose a]
subtrees (_ :> rs) = rs

label :: Rose a -> a
label (a :> _) = a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM