Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between '->' and 'do' in a for loop, in F#

Tags:

f#

I can do this:

[ for i in 0 .. 5 -> i ]

or

[ for i in 0 .. 5 do i ]

but, while I can do this:

[ for i in 0 .. 5 do yield! [i * 4; i] ]

I can't do that:

[ for i in 0 .. 5 -> yield! [i * 4; i] ]

why is that? how are the two treated differently?

like image 354
Thomas Avatar asked Apr 28 '20 21:04

Thomas


People also ask

What is the difference between i i 1 and i += 1 in a for loop?

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1 .

What is difference between while loop and for loop?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.

What is the difference between i += 1 and i i 1 in Python?

i+=1 does the same as i=i+1 there both incrementing the current value of i by 1. Do you mean "i += 1"? If so, then there's no difference.

What is N += 1 in Python?

Python does not have unary increment/decrement operator( ++/--). Instead to increament a value, use a += 1. to decrement a value, use− a -= 1.


1 Answers

This is quite tricky, because there are a few things here that F# does implicitly.

First, the -> syntax is really just a shortcut for do yield, so the following translates as:

  [ for i in 0 .. 5 -> i ] 
= [ for i in 0 .. 5 do yield i ]

This explains why you cannot do -> yield! because the translation would result in:

  [ for i in 0 .. 5 -> yield! [i * 4; i] ]
= [ for i in 0 .. 5 do yield (yield! [i * 4; i]) ]

You would have yield! nested inside yield, which makes no sense.

The second tricky thing is the syntax with just do. This is a recent change in F# that makes writing list generators easier (which is fantastic for domain-specific languages that construct things like HTML trees) - the compiler implicitly inserts yield so the code translates as:

  [ for i in 0 .. 5 do i ]
= [ for i in 0 .. 5 do yield i ]

The interesting thing is that this works with multiple yields as well:

  [ for i in 0 .. 5 do 
      i
      i*10 ]

= [ for i in 0 .. 5 do 
      yield i 
      yield i*10 ]

This is another difference between -> and do. With ->, you can only yield one thing. With do, you can yield multiple things.

I imagine that there is very little reason for using -> nowadays. This was in the language before the implicit yield and so it was useful in earlier versions of F#. You probably do not really need that anymore when do makes things as easy.

like image 159
Tomas Petricek Avatar answered Nov 10 '22 20:11

Tomas Petricek