我是F#的新手,想知道列表x
中ys
值multiplicity (2, [1;2;3;4;2])
的次数是多少次
因此,例如let rec multiplicity (x, ys) =
match ys with
| [] -> 0
| y::tail when x=y -> x + multiplicity(x, tail)
| y::tail -> multiplicity(x, tail)
返回2.下面的代码我在下面的示例中返回4。我错过了什么?
LD_PRELOAD
答案 0 :(得分:2)
好的,这是一个很好的例子,说明为什么写下问题/问题总是一个好主意。
我想出来了,我应该这样做:
1
它应该是x
而不是{{1}},它会被添加到递归调用中,doh。
答案 1 :(得分:2)
如果您不是将此作为递归函数编写为学习练习,则使用内置集合函数可能更为惯用:
[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)
答案 2 :(得分:0)
我觉得用fold替换递归是个好主意,所以这是另一个版本:
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)