F#组合两个序列

时间:2018-01-06 22:23:34

标签: f# functional-programming sequences

我有两个序列,我想以某种方式结合,因为我需要在第一个旁边打印第二个的结果。代码当前是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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:7)

正如Foggy Finder在评论中所说,在你的具体情况下,你真的没有两个序列,你有一个序列,你想为每个项打印两行,这可以用一个{{{ 1}}像这样:

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

这会将以下三行打印到控制台:

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更有用之外,原因超出了这个答案的范围。搜索Stack Overflow for" [F#] unit"你应该找到一些有趣的问题和答案,例如this one