F# 压缩实现
F# zip implementation
我不知道如何在 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"]
是一个包含一个元素的列表,该元素是 4 维元组。这就是为什么您从 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
我不知道如何在 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"]
是一个包含一个元素的列表,该元素是 4 维元组。这就是为什么您从 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