Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
F#在函数中创建新列表_F# - Fatal编程技术网

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