2015-09-09 94 views
3

我無法弄清楚如何在F#中實現Zip函數。誰能告訴我我做錯了什麼?以下是我已經輸入到fsi.exeF#zip實現

> 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"))] 
+0

備選: 讓REC ZIP2 XS YS = 比賽XS,與 YS | XH :: XT,YH :: YT - >(XH,YH)::(zip2 xt yt) | _,_ - > [] https://dotnetfiddle.net/9TkL3k –

回答

8

在您的例子["a","b","c","d"]是包含一個元素,這是4維的元組的列表。這就是爲什麼你從zip獲得意想不到的結果。 改爲使用;作爲元素分隔符。

1

我認爲值得指出的是,爲了避免在較大的列表上出現堆棧溢出,可能值得使用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