F#在函数中创建新列表
这是我当前的函数,我一直在研究如何创建一个新的列表并返回该列表,我想用它来测试我的函数F#在函数中创建新列表,f#,F#,这是我当前的函数,我一直在研究如何创建一个新的列表并返回该列表,我想用它来测试我的函数 let rec findMatches str list = let hd :: tl = list match list with | [] -> [] | (s, _) as hd :: tl when s = str -> hd :: findMatches str tl | _::tl -> findM
let rec findMatches str list =
let hd :: tl = list
match list with
| [] -> []
| (s, _) as hd :: tl when s = str -> hd :: findMatches str tl
| _::tl -> findMatches str tl
我想让它重聚
matchs "A" [("A",5); ("BB",6); ("AA",9); ("A",0)];;
因此,我知道我需要返回一个int列表使用带有累加器参数的递归内部函数逐个收集结果很容易实现您的目标:
val it : int list = [0; 5]
这是使用F#库中的
List.fold
的最佳选择
let findMatches str list =
let rec inner acc = function
| [] -> acc
| (s, n) :: tl ->
inner (if s = str then n :: acc else acc) tl
inner [] list
let toMatch = "A"
let test =
[ ("A", 5)
("BB", 6)
("AA", 9)
("A", 0) ]
let findMatches toMatch items =
List.fold
(fun output item ->
if toMatch = (fst item) then
(snd item) :: output //Append if we find a match otherwise just return the same list
else
output)
[] //Set initial output to the empty list
items
findMatches toMatch test