开发者

Calling BCL functions with tuple arguments in F#

From what I've read, and if I am not mistaken, it seems that any BCL method receives its arguments as a tuple in F#. So I was wondering if instead of having

let rndNumber= rng.Next(-10, 10)

I could have something along the lines of

let range = (-10, 10)
let rndNumber = rng.Next range

the full code is the following:

open System
let rng = new Random()
let range = (-10, 10)
let rndNumber = rng.Next range

and the error I'm getting is

This expressi开发者_StackOverflowon was expected to have type
    int    
but here has type
    int * int    


You could have a .NET method overload that takes a single argument of type System.Tuple as well, which complicates matters.

In general, F# looks at the call site of the method, and syntactically determines which overloads to try. When you call o.M aTupleVar F# tries to find a method taking a single argument (that is a tuple), as opposed to multiple arguments.

The "piping" workaround Daniel suggested works because there is no syntactic call to a method, so F# just resolves rng.Next to the overload group of methods with that name, and resolves the call later.

That said, there is almost never a reason in practice to do this. If you're going to call a .NET method, do it directly with o.M(arg1,arg2), there is rarely a need/desire to create a tuple first.


Try this instead:

let rndNumber = range |> rng.Next

I think the lack of type information at the point of the method call is causing it to default to the first overload (accepting int). If you pipe your argument to it, it knows which overload you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜