在 F# 中使用元组参数调用 BCL 函数
根据我所读到的内容,如果我没有记错的话,似乎任何 BCL 方法都将其参数作为 F# 中的元组接收。所以我想知道我是否
let rndNumber= rng.Next(-10, 10)
可以有一些类似的东西
let range = (-10, 10)
let rndNumber = rng.Next range
完整的代码如下:
open System
let rng = new Random()
let range = (-10, 10)
let rndNumber = rng.Next range
我得到的错误是
This expression was expected to have type
int
but here has type
int * int
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 expression was expected to have type
int
but here has type
int * int
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能有一个 .NET 方法重载,它也采用 System.Tuple 类型的单个参数,这会使问题变得复杂。
一般来说,F# 会查看方法的调用位置,并从语法上确定要尝试哪些重载。当您调用 oM aTupleVar 时,F# 尝试查找采用单个参数(即元组)而不是多个参数的方法。
Daniel 建议的“管道”解决方法之所以有效,是因为没有对方法的语法调用,因此 F# 只是将
rng.Next
解析为具有该名称的方法重载组,并稍后解析调用。也就是说,实际上几乎没有理由这样做。如果您要调用 .NET 方法,请直接使用
oM(arg1,arg2)
来执行,很少需要/渴望先创建一个元组。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.试试这个:
我认为方法调用时缺少类型信息导致它默认为第一个重载(接受 int)。如果您将参数传递给它,它就会知道您想要哪个重载。
Try this instead:
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.