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?
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 .
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.
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.
Python does not have unary increment/decrement operator( ++/--). Instead to increament a value, use a += 1. to decrement a value, use− a -= 1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With