在 F# 中使用元组参数调用 BCL 函数

发布于 2024-11-30 02:13:24 字数 504 浏览 0 评论 0原文

根据我所读到的内容,如果我没有记错的话,似乎任何 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

|煩躁 2024-12-07 02:13:24

您可能有一个 .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.

冰之心 2024-12-07 02:13:24

试试这个:

let rndNumber = range |> rng.Next

我认为方法调用时缺少类型信息导致它默认为第一个重载(接受 int)。如果您将参数传递给它,它就会知道您想要哪个重载。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文