提问人:TJ8 提问时间:4/24/2017 更新时间:4/24/2017 访问量:96
F# 需要重写代码以不需要可变变量
F# Need to rewrite code to not require a mutable variable
问:
我已经完成了我一直在做的项目,但我想回去清理我的代码。在这个例子中,我使用了一个可变变量,但是我希望我的代码不包含可变变量。我将如何重写此代码部分以返回布尔值但使其不可变?
let mutable duplicates = false
for el in (combo|>Seq.head) do
let exists = Seq.exists (fun x -> x = el) (combo|>Seq.item 1)
duplicates <- exists
任何帮助将不胜感激,干杯!
答:
1赞
Lee
4/24/2017
#1
let s1 = combo |> Seq.head
let s2 = combo |> Seq.item 1
let duplicates = System.Linq.Enumerable.Intersect(s1, s2) |> Seq.isEmpty |> not
评论
0赞
TJ8
4/24/2017
感谢您的回复,这有效,但我选择了另一个回复,因为它对我来说更简单并且不需要使用 Linq。
4赞
ildjarn
4/24/2017
#2
let t = Seq.item 1 combo
let duplicates = Seq.head combo |> Seq.exists (fun el -> Seq.contains el t)
关于以这种方式处理 s 的通常警告适用。seq
评论
0赞
TJ8
4/24/2017
欣赏答案,完美工作!在我的项目中,效率低下并不重要。
评论