According to the F# spec (see §6.5.7), simple for loops are bounded by integer (int
aka int32
aka System.Int32
) limits start
and stop
, e.g.
for i = start to stop do
// do sth.
I wonder why the iteration bounds for this type of for loop are required to be int32
. Why not allow uint32
? int64
? bigint
?
I'm aware that sequence iteration expressions (for ... in ...
) can iterate over arbitrary sequences; that however requires allocating an iterator and calling MoveNext
and Current
and what not and can thus be considerably less efficient than a plain loop could be (increment counter, compare, conditonal jump). To avoid that, you are stuck with using while
and a manually incrementing loop counters...
Strangely enough, F# does allow non-int32
loop bounds, if the for
expression is wrapped in a sequence expression, e.g.
seq { for i = 0I to 10I do
printfn "%A" i }
So, I guess the question is: Is there a particular reason for only allowing int32
for loops? And why does this restriction not apply to for
loops wrapped in seq
expressions?
int
as a general-purpose integer, including its use in all sorts of numerical indexing scenarios. Example: msdn.microsoft.com/en-us/library/…. Counter-example: msdn.microsoft.com/en-us/library/…, which uses a long. – Tabathabreak
/return
). Within a computation expressionfor
is desugared to a method call, which isn't inherently imperative like a loop, and therefore doesn't have the same limits. I can understand the mystery though. +1 – Zawdeseq { for .. to .. do .. }
andseq { for .. in .. do }
is largely identical, both are transformed to aGeneratedSequenceBase<_>
enumerator. – Niles