List 在列表中查找元素
我构建了一个简单的函数,告诉我给定元素在列表中的实际位置。第一个位置是0:List 在列表中查找元素,list,f#,List,F#,我构建了一个简单的函数,告诉我给定元素在列表中的实际位置。第一个位置是0: let rec foo79 = fun k l -> match k, l with | k, [] -> failwith "What you are lookig for is not here" | k, (x::xs) -> if x = k then 0 else 1 +
let rec foo79 =
fun k l ->
match k, l with
| k, [] -> failwith "What you are lookig for is not here"
| k, (x::xs) -> if x = k then 0
else 1 + foo79 k xs
它很简单而且有效(即使如此,每一个改进它的建议都是受欢迎的!)
使用此函数,我没有做到的是,如果列表中出现了多次x
,则让它告诉我x
的位置。
到目前为止,我的尝试甚至没有接近解决方案。实际上,我发布它只是为了让你成为我追求的方法的一个例子
let rec foo79b =
fun k l ->
match k, l with
| k, [] -> failwith "What you are lookig for is not here"
| k, (x::xs) -> if x = k & (x::xs) then 1 + foo79b k xs
elif x = k & [] then 0
else 1 + foo79b k xs
您的函数将需要返回一个位置列表,因此您可以使用累加器来生成列表。同时,您可以使用另一个辅助参数来处理索引,而不必在调用站点求和:
let findAllPos elem lst =
let rec foo79 =
fun k l i acc ->
match k, l with
| k, [] -> acc
| k, (x::xs) -> if x = k then foo79 k xs (i+1) (i::acc)
else foo79 k xs (i+1) acc
foo79 elem lst 0 []
这样,它变得更简单,更重要的是使您的解决方案。如果您不相信我,请尝试像这样调用您的第一个函数
foo79 400000[0..400000]
,然后尝试我建议的函数findAllPos 400000[0..400000]
我没有想到创建一个列表作为输出。谢谢你宝贵的建议!谢谢你的例子!
let positions (x: 'a) (xs: 'a seq) : int seq =
xs
|> Seq.mapi (fun i y -> if y = x then Some i else None)
|> Seq.choose id
// [0; 0; 2; 3; 4; 0; 6] |> positions 0;;
// val it : seq<int> = seq [0; 1; 5]
let positions' (x: 'a) (xs: 'a list) : int list =
[0..(Seq.length xs - 1)]
|> List.filter (fun i -> xs.[i] = x)
// [0; 0; 2; 3; 4; 0; 6] |> positions' 0;;
// val it : int list = [0; 1; 5]