Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a list of items after its constructed

Tags:

c#

list

f#

Please understand I just started programming F# Yesterday.

I have this algorithm in c# where I have a list of Nodes and those nodes have a list of children.

How can I achieve this? I know F# deals with immutable types and change a variable/object is not encouraged. What is a good way to go about it?

C#

public class Node
{
    public List<Node> childrenNode = new List<Node>();
    public void AddChildren(Node node)
    {
        childrenNode.Add(node);
        node.Parent(this);
    }
}

F#

type Node(board:Board)=
     let mutable _childrenNode= Set.empty
     new() = Node()
     member AddChildren(node:Node)=
like image 277
Taufiq Abdur Rahman Avatar asked Mar 23 '23 05:03

Taufiq Abdur Rahman


2 Answers

The simplest way to represent tree structures in F# is to use discriminated unions. Here's an example that also adds the ability to store a value in each node:

type Tree<'T> =
    | Empty
    | Node of option<'T> * List<Tree<'T>>

So, the Tree type consists of two cases - either it's an empty tree or a node with an optional value and a list of children.

The data type is immutable so the add function requires you to pass an existing tree along with a list of additional nodes:

let addChildren (nodes: list<Tree<'T>>) (tree: Tree<'T>) : Tree<'T> =
    match tree with
    | Empty        -> Node (None, nodes)
    | Node (v,chs) -> Node (v, chs @ nodes)

Pattern matching is used to distinguish between the two shapes of Tree values.

like image 140
esevelos Avatar answered Mar 24 '23 22:03

esevelos


Try this out:

type Node() as this =
    let children = new ResizeArray<Node>()
    let mutable parent : Node = this
    member this.Parent with get() = parent
    member this.AddChild(node : Node) =
       children.Add(node)
       node.Parent <- this

this is effectively the same thing as your C# code, although like you said, it does go pretty strongly against the F# mindset.

like image 45
sircodesalot Avatar answered Mar 25 '23 00:03

sircodesalot