Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
843 views
in Technique[技术] by (71.8m points)

list comprehension in 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)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • Nested for loops require a do.

  • You need to use seq {..}. The form {..} without seq doesn't work anymore.

  • A when guard in a for loop pattern is also not supported anymore.

  • print_any something is deprecated. Use printf "%A" something instead.

This code should work:

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]

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...