gpt4 book ai didi

f# - 将数组映射到上一个、当前和下一个值的元组数组

转载 作者:行者123 更新时间:2023-12-01 06:34:20 26 4
gpt4 key购买 nike

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

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

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

?

最佳答案

我更喜欢基于惯用组合器的方法:在数组的两端附加一个空字符串,使用 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", "")|]

关于f# - 将数组映射到上一个、当前和下一个值的元组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20754905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com