Call a function from its name as a string in f #

I thought I could do it with quotes, but I don’t see how to do it.

Should I just use a function table with their names or is this a way to do this?

Thank.

More details ...

I call a lot of f # functions from excel and I was wondering if I can write a f # function

let fs_wrapper (f_name: string) (f_params: list double) = this bit calls fname with f_params

and then use

= fs_wrapper ("my_func", 3.14, 2.71)

rather than wrapping all functions separately.

+5
source share
3 answers

.NET Reflection. , .NET MethodInfo, . ( ) , , ( ).

(, ) - :

module Functions =
  let sin x = sin(x)
  let sqrt y = sqrt(y)

open System.Reflection

let moduleInfo = 
  Assembly.GetExecutingAssembly().GetTypes()
  |> Seq.find (fun t -> t.Name = "Functions")

let name = "sin"
moduleInfo.GetMethod(name).Invoke(null, [| box 3.1415 |])

- , , , :

let funcs = 
  dict [ "sin", Functions.sin;
         "sqrt", Functions.sqrt ]

funcs.[name](3.1415)
+9

, Reflection, :

typeof<int>.GetMethod("ToString", System.Type.EmptyTypes).Invoke(1, null)
typeof<int>.GetMethod("Parse", [|typeof<string>|]).Invoke(null, [|"112"|])

GetMethod , , , .

+2

Following what Thomas mentioned, see Using and abusing the F # dynamic search operator Matthew Subscriptions. It offers a syntactically clean way to dynamically search in F #.

+1
source

All Articles