Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop not inferring unsigned integer [duplicate]

Tags:

for-loop

f#

According to the MSDN documentation on the for ... to loop in F#:

The type of the identifier is inferred from the type of the start and finish expressions. Types for these expressions must be 32-bit integers.

But, with the code below, I get the following compile-time error:

for bar = 0u to 5u do
    let baz : uint32 = bar
    ()
error FS0001: This expression was expected to have type
    int    
but here has type
    uint32

If I put the loop inside a sequence, though, it compiles without error:

let foo =
    seq {
        for bar = 0u to 5u do
            let baz : uint32 = bar
            yield baz
    }
val foo : seq<uint32>

What's going on? Why does the for-loop infer uint32 in the second example but not the first?

I have an external library which takes an unsigned 32-bit integer as an index. I need to iterate from 0 to the length of the collection (also uint32) minus one. When I put this logic inside a sequence and yield each item, it compiles without any errors and runs just fine. But when I attempt to read all the items outside a sequence, the compiler bombs. I'm forced to perform type convers from uint32 to int and back again, which, in my opinion, has a very bad smell to it.

like image 965
JDB Avatar asked Apr 30 '26 21:04

JDB


1 Answers

As explained in this comment by Daniel,

... Within a computation expression for is desugared to a method call, which isn't inherently imperative like a loop, and therefore doesn't have the same limits. ...

Here's a simple work-around:

for bar in 0u .. 5u do
    let baz : uint32 = bar
    ()
like image 73
4 revsJDB Avatar answered May 03 '26 18:05

4 revsJDB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!