Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 852
Yin Zhu Avatar asked Dec 11 '09 14:12

Yin Zhu


People also ask

How do you use an F string in a list in Python?

You can use mathematical operators, call functions, round numbers and basically use any arbitrary one liner Python expression within the curly braces in f-strings. text = f"""This is a rounded number: {points:. 3f} | This is a ten character wide string: "{name:10}". """

Are list comprehensions functional?

One of the language's most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code.

What is list comprehension method?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list.

What is list comprehension give an example?

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.


1 Answers

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

like image 124
cfern Avatar answered Sep 22 '22 22:09

cfern