gpt4 book ai didi

F# 组合两个序列

转载 作者:行者123 更新时间:2023-12-01 04:33:13 25 4
gpt4 key购买 nike

我有两个序列,我想以某种方式组合它们,因为我需要在第一个序列旁边打印第二个序列的结果。代码当前是 playerItems 引用列表的地方:

seq state.player.playerItems
|> Seq.map (fun i -> i.name)
|> Seq.iter (printfn "You have a %s")

seq state.player.playerItems
|> Seq.map (fun i -> i.description) |> Seq.iter (printfn "Description = %s")

目前的结果是
You have a Keycard
You have a Hammer
You have a Wrench
You have a Screw
Description = Swipe to enter
Description = Thump
Description = Grab, Twist, Let go, Repeat
Description = Twisty poke

但是,我需要它
You have a Keycard
Description = Swipe to enter
You have a Hammer
Description = Thump

对此的任何帮助将不胜感激。

最佳答案

正如 Foggy Finder 在评论中所说,在您的特定情况下,您确实没有两个序列,您只有一个序列,并且您想为每个项目打印两行,这可以通过一个 Seq.iter 来完成。像这样:

state.player.playerItems  // The "seq" beforehand is not necessary
|> Seq.iter (fun player -> printfn "You have a %s\nDescription = %s" player.name player.description)

但是,我也会告诉您组合两个序列的两种方法,当您确实有两个不同的序列时。首先,如果你想把两个序列变成一个元组序列,你可以使用 Seq.zip :
let colors = Seq.ofList ["red"; "green"; "blue"]
let numbers = Seq.ofList [25; 73; 42]
let pairs = Seq.zip colors numbers
printfn "%A" pairs
// Prints: seq [("red", 25); ("green", 73); ("blue", 42)]

如果您想以其他方式组合两个序列而不是生成元组,请使用 Seq.map2并传递给它一个两个参数的函数:
let colors = Seq.ofList ["red"; "green"; "blue"]
let numbers = Seq.ofList [25; 73; 42]
let combined = Seq.map2 (fun clr num -> sprintf "%s: %d" clr num) colors numbers
printfn "%A" combined
// Prints: seq ["red: 25"; "green: 73"; "blue: 42"]

最后,如果您只想对两个序列中的每对项目执行一些副作用,那么 Seq.iter2是你的 friend :
let colors = Seq.ofList ["red"; "green"; "blue"]
let numbers = Seq.ofList [25; 73; 42]
Seq.iter2 (fun clr num -> printfn "%s: %d" clr num)

这会将以下三行打印到控制台:
red: 25
green: 73
blue: 42

注意如何在 Seq.iter函数,我不存储结果。那是因为 Seq.iter 的结果总是 () ,相当于 F# 的“单位”值 void . (除了它比 void 有用得多,原因超出了本答案的范围。在 Stack Overflow 中搜索“[F#] unit”,您应该会找到一些有趣的问题和答案,例如 this one

关于F# 组合两个序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132514/

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