在 F# 中迭代嵌套序列 - 如何?
我可以在 F# 中定义一个简单列表,如下所示,并使用以下代码对其进行迭代:
let ar = [0;1;2;3]
ar |> Seq.iter (fun x -> printfn "Ar: %A" x)
现在考虑一个嵌套序列,如下所示:
let ar1 = [1;2;3;4]
let ar2 = [5;6;7;8]
let nested_array = [ar1; ar2]
我如何迭代此列表 - 下面的代码出现错误:
“lambda 表达式中出现意外的中缀运算符”
我在这里要做的是迭代外部序列并将其转发到第二个迭代器,然后让我访问内部数组的内容。
nested_array |>
Seq.iter (fun x -> |>
Seq.iter (fun y ->
printfn "Ar: %A" y))
我在这里缺少什么 - 我怀疑语法问题或(更严重/可能)缺乏 F#/FP 理解。
I can define a simple list in F# as follows and iterate over it with the following code:
let ar = [0;1;2;3]
ar |> Seq.iter (fun x -> printfn "Ar: %A" x)
Now consider a nested sequence as follows:
let ar1 = [1;2;3;4]
let ar2 = [5;6;7;8]
let nested_array = [ar1; ar2]
How can I Iterate over this - the following code below gets an error:
'Unexpected infix operator in lambda expression'
What I'm trying to do here is to iterate over the outer sequence and pipe that forward to a second iterator which then lets me access the contents of the inner arrays.
nested_array |>
Seq.iter (fun x -> |>
Seq.iter (fun y ->
printfn "Ar: %A" y))
What am I missing here - I suspect a syntax problem or (more serious/likely) a lack of F#/FP comprehension .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有使用变量
x
。尝试“或”(完全消除
x
的使用)或什至(也消除
y
)You're not using your variable
x
. Try eitheror (eliminating the use of
x
entirely)or even (eliminating
y
as well)我通常不喜欢使用
seq.iter
函数,当它不在较大的处理管道的一部分中时。替代方法是仅将nested用于
:尽管使用部分功能应用程序(如KVB发布)是真的,这只是个人喜好的问题 - 您期望谁阅读它。我想我的方法不是使源代码“更聪明”,如果它没有给您任何明确的价值。
I don't generally like using
Seq.iter
function when it is not in a part of a larger processing pipeline. The alternative is to just use nestedfor
:Although, it's true that using partial function application (as posted by kvb) nakes it quite nice, so it is just a matter of personal preference - and who you expect to read it. I guess my approach is not to make the source code "more clever" if it doesn't give you any clear value.
试试这个。
嵌套数组 |> Seq.iter (fun x -> x |> Seq.iter (printfn "%d"))
Try this.
nested_array |> Seq.iter (fun x -> x |> Seq.iter (printfn "%d"))