applying a list to a function's arguments

f#, function, functional-programming, list

Solution

You can write a function like `apply` that takes any F# function and an array of arguments and invokes the function via Reflection.

However, there is a good reason why this is not in the standard F# library - one of the strengths of F# (compared e.g. to Mathematica) is that it is statically typed language and can catch most potential errors at compile time. If you use something like `apply` then you'll lose this checking [because you never know if the list has the right length].

Nevertheless, here is an example of how to do this:

open Microsoft.FSharp.Reflection

let apply (f:obj) (args:obj[]) =
  if FSharpType.IsFunction(f.GetType()) then
    let invoke =
      f.GetType().GetMethods()
      |> Seq.find (fun mi -> mi.Name = "Invoke" && mi.GetParameters().Length = args.Length)
    invoke.Invoke(f, args)
  else failwith "Not a function"

Sample use looks like this:

let add a b = a + b;;
apply add [| 3;4 |];;

Problem

How to write a function in F# for applying a list of values to a function like the `Apply` (@@) symbol in mathematica (map elements of the list to function arguments) for example `apply f [1;2;3]` calls `f(1,2,3)` or as in curried function application `f 1 2 3`

Original source