25

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)

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.

4

1 回答 1

31
  • 嵌套的 for 循环需要一个do.

  • 你需要使用seq {..}. {..}没有的表格seq不再起作用。

  • 也不再支持循环模式中的when守卫。for

  • print_any something已弃用。改为使用printf "%A" something

此代码应该可以工作:

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)

->如果您只想返回一个值,您仍然可以使用:

let vec1 = [1;2;3]
let vec2 = [4;5;6]
let products = [for x in vec1 do for y in vec2 -> x*y]

顺便说一句,我觉得看看 F# 如何随时间演变很有趣。太糟糕了,早期采用者的书架上有部分过时的书籍(我不介意)。

于 2009-12-11T16:17:39.003 回答