说我们有一个收藏集
let xs = ["1";"2"]
我们可以遍历其元素
let forXs =
[ for x in xs do
yield x ]
或者我们可以使用map
let mapXsWithId = List.map id xs
let mapXLambda = List.map (fun x -> x) xs
说我们有很多集合,每个集合的长度可能不同
let xs = ["1";"2"]
let ys = ["a";"b";"c"]
let zs = ["1";"2";"3";"4"]
我们可以通过这种方式获得所有元素的组合
let combinations =
[ for x in xs do
for y in ys do
for z in zs do
yield x + y + z ]
我们能以更实用的方式做到这一点吗?
答案 0 :(得分:2)
你可以
let xs = ["1";"2"]
let ys = ["a";"b";"c"]
let zs = ["1";"2";"3";"4"]
let combinations =
xs
|> List.collect (fun x ->
ys
|> List.collect (fun y ->
zs
|> List.map (fun z -> x + y + z)))
问题是,这是否比您的解决方案好得多。
答案 1 :(得分:0)
在@TeaDrivenDev的基础上,将集合名称(xs
)与操作(List.
)放在同一行,使它看起来更等效。
let combinations =
xs |> List.collect (fun x ->
ys |> List.collect (fun y ->
zs |> List.map (fun z -> x + y + z)))
let combinations2 =
[ for x in xs do
for y in ys do
for z in zs do
yield x + y + z ]