3

How do I implement a method with a variable number of arguments?

In C#, we can use the params keyword:

public class MyClass
{
    public static void UseParams(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }
 }

So how can I do this in F#?

type MyClass() =

    member this.SomeMethod(params (args:string array)) = ()

I receive the following error from the code above:

The pattern discriminator 'params' is not defined
Guy Coder
  • 24,501
  • 8
  • 71
  • 136
Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • Possible duplicate of [In F#, how do you curry ParamArray functions (like sprintf)?](http://stackoverflow.com/questions/11145680/in-f-how-do-you-curry-paramarray-functions-like-sprintf) – FoggyFinder Mar 09 '17 at 23:25

1 Answers1

10

You can use ParamArrayAttribute:

type MyClass() =
    member this.SomeMethod([<ParamArray>] (args:string array)) = Array.iter (printfn "%s") args

then:

let mc = MyClass()
mc.SomeMethod("a", "b", "c")
Lee
  • 142,018
  • 20
  • 234
  • 287