F#中的列表理解 [英] list comprehension in F#
问题描述
我正在尝试在 F# 中进行一些列表理解.我发现了这个.
I am trying to do some list comprehension in F#. And I found this.
let evens n =
{ for x in 1 .. n when x % 2 = 0 -> x }
print_any (evens 10)
let squarePoints n =
{ for x in 1 .. n
for y in 1 .. n -> x,y }
print_any (squarePoints 3)
第一个仍然可以正常工作,但第二个已经过时了.最新的 (1.9.7.8) F# 编译器不支持这种风格.
The first still works ok, but the second is outdated. The latest (1.9.7.8) F# compiler does not support this style.
经过一番搜索,我发现这个作品
After some search I found this works
let vec1 = [1;2;3]
let vec2 = [4;5;6]
let products = [for x in vec1 do for y in vec2 do yield x*y]
有人能指出为什么语法改变了吗?谢谢.
Can someone point why the syntax changed? Thanks.
推荐答案
嵌套 for 循环需要
do
.您需要使用
seq {..}
.没有seq
的形式{..}
不再起作用.You need to use
seq {..}
. The form{..}
withoutseq
doesn't work anymore.也不再支持
for
循环模式中的when
保护.A
when
guard in afor
loop pattern is also not supported anymore.print_any something
已弃用.使用printf "%A" something
代替.print_any something
is deprecated. Useprintf "%A" something
instead.此代码应该可以工作:
let evens n = seq { for x in 1 .. n do if x%2=0 then yield x } printf "%A" (evens 10) let squarePoints n = seq { for x in 1 .. n do for y in 1 .. n -> x,y } printf "%A" (squarePoints 3)
如果您只想返回单个值,您仍然可以使用
->
:You can still use the
->
if all you want to do is return a single value:let vec1 = [1;2;3] let vec2 = [4;5;6] let products = [for x in vec1 do for y in vec2 -> x*y]
顺便说一下,我觉得看看 F# 如何随着时间的推移而发展很有趣.太糟糕了,早期采用者的书架上有部分过时的书籍(我并不介意).
By the way, I find it interesting to see how F# evolved over time. Too bad the early adopters have partially outdated books on their shelves (not that I mind).
这篇关于F#中的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!