在循環內我添加了一個新元素到列表中,我需要在下一次迭代中使用可變的.Net List<T>
。F#:是否可以使用可變.Net列表添加元素到同一個列表
F#
鼓勵在一般情況下使用不可變集合,並且似乎我無法實現我想要的使用immutable list
或seq
。
繼續使用可變的.Net List<T>
還是可以接受的,還是鼓勵只使用不可變的?如果是的話,我怎麼能實現呢?
我的代碼是有點長而複雜,所以讓我們考慮這個僞F#代碼:
let children = new List<node>()
let bestBranchEntropies = entropiesSuchAs data.Rows parents
//Finding the best children for the best parent
bestBranchEntropies |> Seq.iter (fun bestBranch -> let attribut = IGetTheAttributByMaximumGainHere
//Creating one of the children in every iteration
let node = {
content = attribut;
branch = Some(fst bestBranch);
children = None;
isLeaf = false;
}
//Considering it a child
children.Add node
)
//After having all the children
let children' = children |> Seq.map (fun child -> {
content = child.content;
branch = child.branch;
children = //recursive call here to do the same work above (getting children again, yeah it's a tree)
isLeaf = child.isLeaf;
})
Some(children')
「可接受」是非常主觀的。話雖如此:可以接受嗎?最有可能的。必要?很可能不會。更快使用可變嗎?不清楚。如果你給更多的上下文,你會得到更好的答案。你如何建立清單?你怎麼使用它? –
F#具有可變列表類型的特殊類型縮寫,因此可以使用它。 –
幾乎可以肯定地有一種不變的選擇,如果你給我們提供了一些背景知識,我們可以解釋一下。 – TheInnerLight