【问题标题】:F# zip implementationF# zip 实现
【发布时间】:2015-12-06 00:17:47
【问题描述】:

我不知道如何在 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"))]

【问题讨论】:

  • 替代方案:让 rec zip2 xs ys = 匹配 xs,ys 和 |xh::xt,yh::yt -> (xh,yh)::(zip2 xt yt) |_,_ - > []dotnetfiddle.net/9TkL3k

标签: f# functional-programming f#-interactive


【解决方案1】:

在您的示例中,["a","b","c","d"] 是一个包含一个元素的列表,该元素是 4 维元组。这就是为什么你会从 zip 中得到意想不到的结果。 只需使用; 作为元素分隔符即可。

【讨论】:

    【解决方案2】:

    我认为值得指出的是,将 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
    

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      • 2015-06-08
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多