For loop not inferring unsigned integer [duplicate]

跟風遠走 提交于 2019-12-12 12:43:59

问题


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.


回答1:


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
    ()


来源:https://stackoverflow.com/questions/21292082/for-loop-not-inferring-unsigned-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!