[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.