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)=
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With