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

后端 未结 6 1011
南方客
南方客 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:40

    Look into using the Functor instance of the Maybe type.

    For example, maybe your problem is something like this: you want to insert an element into a binary tree, but only if it isn't already present. You could do that with something like:

    data Tree a = Node a (Tree a) (Tree a)
                | Tip
    
    maybeInsert :: a -> Tree a -> Maybe (Tree a)
    maybeInsert a Tip = Just $ Node a Tip Tip
    maybeInsert a (Node a' l r)
        | a == a' = Nothing
        | a < a'  = fmap (\l'-> Node a' l' r) (maybeInsert a l)
        | a > a'  = fmap (\r'-> Node a' l r') (maybeInsert a r)
    

    So the function will return Nothing if we found the element to be already present, or return Just the new tree with the element inserted.

    Hopefully that is relevant to whatever you are trying to do.

提交回复
热议问题