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#zip实现_F#_Functional Programming_F# Interactive - Fatal编程技术网

F#zip实现

F#zip实现,f#,functional-programming,f#-interactive,F#,Functional Programming,F# Interactive,我不知道如何在F#中实现Zip函数。谁能告诉我我做错了什么?以下是我在fsi.exe中键入的内容: > let rec zip xs ys = - match xs with - | [] -> [] - | head :: tail -> (match ys with - | [] -> [] - | headY :: tailY -> (head, headY) :

我不知道如何在F#中实现Zip函数。谁能告诉我我做错了什么?以下是我在
fsi.exe中键入的内容:

> let rec zip xs ys =
-  match xs with
-   | [] -> []
-   | head :: tail -> (match ys with
-                       | [] -> []
-                       | headY :: tailY -> (head, headY) :: zip tail tailY);;

val zip : xs:'a list -> ys:'b list -> ('a * 'b) list

> zip [1;2;3;4] ["a","b","c","d"];;
val it : (int * (string * string * string * string)) list =
  [(1, ("a", "b", "c", "d"))]
在您的示例中,
[“a”、“b”、“c”、“d”]
是一个包含一个元素的列表,该元素是四维元组。这就是为什么您会从zip中得到意想不到的结果。
只要使用
改为元素分隔符。

我认为值得指出的是,让
zip
函数尾部递归也是值得的,这样可以避免较大列表上的堆栈溢出

也许是这样的

let zip3 xs ys = 
  let rec loop r xs ys =
    match xs,ys with 
    | [],[]         -> r
    | xh::xt,yh::yt -> loop ((xh,yh)::r) xt yt
    | _ -> failwith "xs & ys has different length"
  loop [] xs ys |> List.rev

备选方案:让rec zip2 xs ys=将xs,ys与| xh::xt,yh::yt->(xh,yh)::(zip2 xt yt)|,|->[]