How do I code a tree of objects in Haskell with pointers to parent and children?

后端 未结 6 889
南方客
南方客 2021-02-06 06:49

I\'ve got the following problem: I have a tree of objects of different classes where an action in the child class invalidates the parent. In imperative languages, it is trivial

6条回答
  •  你的背包
    2021-02-06 07:54

    To answer the question in your title: Yes, you can create nodes which have links to their parents as well as their children. Example:

    --               parent       children
    data Tree = Node (Maybe Tree) [Tree]
    root = Node Nothing [a,b] -- I can "forward reference" a and b because haskell is lazy
    a = Node (Just root) []
    b = Node (Just root) []
    

    The question is whether that's useful for your particular use-case (often times it isn't).

    Now the question in your body: You're right, you can't change a value after it's been created. So once you have a valid tree, you'll always have a valid tree as long as the variable referencing that tree is in scope.

    You didn't really describe what problem you're trying to solve, so I can't tell you how to functionally model what you're trying to do, but I'm sure there's a way without mutating the tree.

提交回复
热议问题