How to implement variable arguments in F #

I want to implement a F # function that can take 1 or 2 arguments. I would like to use the function as follows:

let foo = ...
foo "a"
foo "a" "b"

Both arguments can be of the same type. I have read the pages about the matching pattern, the active pattern, but cannot find what works for me.

+5
source share
4 answers

In addition to the other answers, you can also do what you want with a partial application and currying. Like this:

let foo a b =
   a + b

let foo2 a =
   foo 1 a;;

Obviously, you want to fix the first parameter in a call to foo inside foo2 by default, which you want.

+2
source

, .Net-, , - -

 type t() =
     static member foo a = "one arg"
     static member foo (a,b) = "two args"
+7

:

type Helper private () =
    static member foo (input1, ?input2) =
          let input2 = defaultArg input2 "b"
          input1, input2

:

Helper.foo("a")
Helper.foo("a", "b")

, ?

You cannot use optional parameters for a function, but unfortunately.

+5
source

In addition to the other answers, here are some more “almost solutions”. They are not strictly what you wanted, but you should still know.

Using a list (or array) and pattern matching:

let f = function
    | [a, b] -> ...
    | [a] -> ...
    | [] -> failwith "too few arguments"
    | _ -> failwith "too many arguments"

f ["a"]
f ["a" ; "b"]

Problems: parameters are not named, it is not clear from the function signature how many parameters are required.

Using a record to pass all optional parameters:

type FParams = { a : string; b : string }
let fdefault = { a = "a" ; b = "b" }

let f (pars: FParams) = ...

f { fdefault with b = "c" }

Problem: a is also optional that you do not need. May be helpful though.

+3
source

All Articles