Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable length tuples in f#

Tags:

f#

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) {
    ...
}
like image 434
whatupdave Avatar asked Jul 16 '09 05:07

whatupdave


2 Answers

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]
like image 90
Pavel Minaev Avatar answered Nov 10 '22 15:11

Pavel Minaev


@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.

like image 35
Brian Avatar answered Nov 10 '22 14:11

Brian