我是F#的新手,我想知道一个值x在list ys中发生了多少次
例如,multiplicity (2, [1;2;3;4;2])返回2,下面编写的代码在上面的示例中返回4。我遗漏了什么?
let rec multiplicity (x, ys) =
match ys with
| [] -> 0
| y::tail when x=y -> x + multiplicity(x, tail)
| y::tail -> multiplicity(x, tail)发布于 2017-10-01 07:20:31
好的,这是一个很好的例子,说明为什么写下一个问题总是一个好主意。
我想,我应该这么做:
let rec multiplicity (x, ys) =
match ys with
| [] -> 0
| y::tail when x=y -> 1 + multiplicity(x, tail)
| y::tail -> multiplicity(x, tail)它应该是1而不是x,它被添加到递归调用doh中。
发布于 2017-10-01 09:07:20
如果您不是将它作为一个递归函数来编写作为一个学习练习,那么使用内置的集合函数可能更有习性:
[1;2;3;4;2] |> Seq.filter ((=) 2) |> Seq.length
[1;2;3;4;2] |> List.sumBy (fun x -> if x = 2 then 1 else 0)发布于 2017-10-01 09:20:44
我发现用折叠代替递归是个好主意,下面是另一个版本:
let xs = [1;2;3;4;2]
(0,xs) ||> List.fold (fun acc elem -> match elem with
| 2 -> acc + 1
| _ -> acc)您还可以使用countBy,它将返回包含true和false的元组列表。
xs |> List.countBy (fun x -> x = 2)https://stackoverflow.com/questions/46510126
复制相似问题