Variable length tuples in f#

穿精又带淫゛_ 提交于 2020-01-03 11:37:10

问题


Is it possible to write a function to accept a tuple of variable length? I'm trying to write a method that can be called like this:

let a = sum(1,2)
let b = sum(1,2,3)

EDIT: Could it be interpreted as a function call with params? Or would the method need to be written in c#:

double sum(params object[] double) {
    ...
}

回答1:


No - tuples are by definition not variable length, and to write a function like this you'd need something like template metaprogramming in C++ - and there isn't such a thing in F#; let inline won't help you there either.

Of course, if you take a list instead, it won't look that much different:

sum[1; 2]
sum[1; 2; 3]



回答2:


@PavelMineav is right, you can't do it, but note that members can be overloaded, a la

type Foo() =
    member this.sum(x,y) = x + y
    member this.sum(x,y,z) = x + y + z

let foo = new Foo()
printfn "%d" (foo.sum(1,2))
printfn "%d" (foo.sum(1,2,3))

whereas let-bound functions cannot.



来源:https://stackoverflow.com/questions/1135580/variable-length-tuples-in-f

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