【问题标题】:F# combining two sequencesF# 组合两个序列
【发布时间】:2018-06-16 09:10:29
【问题描述】:

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

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

【问题讨论】:

  • state.player.playerItems |> Seq.iter (fun player -> printfn "You have a %s\nDescription = %s" player.name player.description)

标签: f# functional-programming sequences


【解决方案1】:

正如 Foggy Finder 在 cmets 中所说,在您的特定情况下,您确实没有两个序列,您有一个序列并且您想为每个项目打印两行,这可以通过单个 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 等效的“单位”值。 (除了它比void 有用得多,原因超出了此答案的范围。在堆栈溢出中搜索“[F#] unit”,您应该会找到一些有趣的问题和答案,例如this one

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    相关资源
    最近更新 更多