在循环内,我将一个新元素添加到下一次迭代中所需的列表中,为此我使用可变的 .Net List<T>
.
F#
一般来说,鼓励使用不可变集合,而且似乎我无法使用不可变来实现我想要的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')
最佳答案
据我所知,当然不需要可变列表(如果您的伪代码完全反射(reflect)了问题)。考虑以下因素:
let children =
bestBranchEntropies
|> Seq.map (fun bestBranch ->
let attribut = IGetTheAttributByMaximumGainHere
//Creating one of the children in every iteration
{
content = attribut;
branch = Some(fst bestBranch);
children = None;
isLeaf = false;
}
|> Seq.toList
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
可以跳过第一个 Seq.toList
,并且您可以一直使用管道。从你的伪代码来看,整个第二个循环实际上可以安全地与第一个循环合并?
关于.net - F# : Is it okay to use mutable .Net List 将元素添加到同一列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42403185/