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) {
...
}
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]
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With