F#Interleave 2列表

时间:2016-09-28 13:54:51

标签: list f#

有没有办法可以合并2个列表

let a = ["a"; "b"; "c"]
let b = ["d"; "b"; "a"]

所以我得到了这个结果

result = ["a"; "d"; "b"; "b"; "c"; "a"]

3 个答案:

答案 0 :(得分:8)

此任务最好由persistentStoreCoordinator解决:

foldBack2

答案 1 :(得分:6)

快速&脏解决方案是将两个列表压缩,然后压平生成的元组:

<!doctype html>
<html ng-app="myApp">
  <head>
    <base href="/">
    <meta charset="utf-8">
    <title translate>title</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="icon" type="image/png" href="images/icon.png">
    <link rel="stylesheet" href="styles/vendor-d41d8cd98f.css">
    <link rel="stylesheet" href="styles/app-2dd2bcbbbd.css">
  <script src="https://maps.google.com/maps/api/js"></script>
  </head>
  <body>
        <main ui-view></main>
  </body>
  <script src="scripts/vendor-83b6c91f4a.js"></script>
   <script src="scripts/app-41321c4301.js"></script>
</html>

这将返回包含交错元素的列表:

let interleave a b =
    List.zip a b |> List.collect (fun (a,b)-> [a;b])

interleave a b;; val it : string list = ["a"; "d"; "b"; "b"; "c"; "a"] 将从两个列表的元素中创建对:

zip

val it : (string * string) list = [("a", "d"); ("b", "b"); ("c", "a")] 会使元组变得扁平化

答案 2 :(得分:3)

为了补充@Panagiotis Kanavos基于标准库的答案,这里有一个手工实现,它应该消耗更少的内存,因为它不构建元组(但仍然需要一个中间列表): / p>

let interleave a b =
    let rec loop acc a b =
        match a, b with
        | [], l | l, [] -> List.rev l @ acc
        // Or if you want to fail when the lengths are different, replace the above with:
        // | [], [] -> acc
        // | [], _ | _, [] -> failwith "interleave: List lengths are different"
        | a :: aa, b :: bb -> loop (b :: a :: acc) aa bb
    loop [] a b |> List.rev

this link中的解决方案不是尾递归的,所以也是次优的)