Applying a List to Function Arguments

How to write a function in F # to apply a list of values ​​to a function, such as the Apply symbol (@@) in mathematics (list map elements for function arguments)

for example apply f [1;2;3] calls f(1,2,3) or as in the application with the map in the application f 1 2 3

+6
source share
1 answer

You can write a function of type apply that takes any F # function and an array of arguments and calls the function through Reflection.

However, there is a good reason why this is not part of the standard F # library - one of the strengths of F # (compared, for example, Mathematica) is that it is a statically typed language and can capture most potential errors during compilation. If you use something like apply , you will lose this check [because you never know if the list has the correct length].

However, 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" 

An example of use looks like this:

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

Source: https://habr.com/ru/post/959010/


All Articles