F#元组作为函数参数

5
有没有办法将元组转换为单独的参数,并将它们放入函数中,而不是绑定到变量上? 类似于:
let nice funOf5 tupleOf5 =
    funOf5 (Tuple.toParameters tupleOf5)

替代

let ugly funOf5 tupleOf5 =
    let (number1, number2, number3, number4, number5) = tupleOf5
    funOf5 number1 number2 number3 number4 number5

谢谢。

3
对于由2或3个元素组成的元组,您可以使用 <||<||| 运算符。 参考链接:https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/operators.%5b-%5bhh-%5d%5b%27t1%2c%27t2%2c%27u%5d-function-%5bfsharp%5d - John Palmer
@John Palmer 感谢你的回答,我知道在使用管道时参数应该写成 (arg1, arg2) 的形式,但我没有想到这本身也是一个元组。 - Feofilakt
请注意,它是 <|| 而不是 <| - John Palmer
是的,通过参数数量来实现。但是对于超过3个参数就无法工作了吗? - Feofilakt
不,标准库仅为3个参数定义了它们。 - John Palmer
@JohnPalmer提供的链接已经失效,这里是另一个链接:https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/ - Jeff
1个回答

8

一种解决方法是在函数定义中使用模式匹配。

这受到了标准库中 |||> 的启发,其解决方案为

let inline (|||>) (x1,x2,x3) f = f x1 x2 x3

那么您可以拥有
let inline funof5 (x1,x2,x3,x4,x5) f = f x1 x2 x3 x4 x5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接