在构造项目列表后更改项目列表
本文关键字:列表 项目 | 更新日期: 2023-09-27 18:33:39
请理解我昨天刚开始编程F#。
我在 c# 中有这个算法,其中我有一个节点列表,这些节点有一个子节点列表。
我怎样才能做到这一点?我知道 F# 处理不可变类型,不鼓励更改变量/对象。什么是好方法?
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)=
在 F# 中表示树结构的最简单方法是使用可区分的联合。以下示例还添加了在每个节点中存储值的功能:
type Tree<'T> =
| Empty
| Node of option<'T> * List<Tree<'T>>
因此,Tree
类型包含两种情况 - 要么是空树,要么是具有可选值和子项列表的节点。
数据类型是不可变的,因此 add 函数要求您传递现有树以及其他节点的列表:
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)
模式匹配用于区分Tree
值的两种形状。
试试这个:
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
这实际上与您的 C# 代码相同,尽管就像您所说,它确实非常违背 F# 思维方式。