将数组映射到先前,当前和下一个值的元组数组

时间:2013-12-24 04:33:07

标签: f#

映射以下内容的最佳方式是什么:

[|"A"; "B"; "C"; "D"|]

[|("","A","B"); ("A","B","C"); ("B","C","D"); ("C","D","")|]

3 个答案:

答案 0 :(得分:5)

我更喜欢基于惯用组合的方法:将空字符串附加到数组的两端,使用Seq.windowed 3生成三个项目的滑动数组序列,最后将每个序列元素映射到元组并转换序列回到阵列:

let conv source =
    Array.concat [[|String.Empty|]; source; [|String.Empty|]] |> Seq.windowed 3
    |> Seq.map (fun x -> x.[0],x.[1],x.[2]) |> Seq.toArray

在FSI收益率下测试conv [|"A";"B";"C";"D"|]

val it : (string * string * string) [] =
  [|("", "A", "B"); ("A", "B", "C"); ("B", "C", "D"); ("C", "D", "")|]

答案 1 :(得分:1)

我会这样做:

let neighbors (xs: _ []) =
  let get i = if i>=0 && i<xs.Length then xs.[i] else ""
  Array.mapi (fun i x -> get(i-1), x, get(i+1)) xs

答案 2 :(得分:0)

这是我第一次看f#所以请原谅我的尝试,如果不正确的话。我也没有f#所以我无法测试这个。但基于Array.map ......

let data = [|"A"; "B"; "C"; "D"|]
let convert = data |> Array.map (fun x -> (char(int x - 1), x, char(int x + 1)))
printfn "Converting to tupels by using map = %A" convert

希望它会指出你正确的方向。