Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching based on the function signature

In F# can you pattern match on a function signature. I want to decorate a number of functions with a function that measures the execution of the function and calls out to statsd. The current function I have is:

let WrapFunctionWithPrefix(metrics:Metric.Client.IRecorder, functionToWrap, prefix) =
    let metricsIdentifier = (sprintf "%s.%s" prefix Environment.MachineName)
    using (metrics.StartTimer(metricsIdentifier)) ( fun metrics -> functionToWrap)

As you can see above, the prefix will vary, and in our application this will vary per function definition. So rather than having to pass in the measure prefix every time I want to do something like the following:

let WrapFunction metrics afunc = 
    match afunc with
    | :? (int -> int) -> WrapFunctionWithPrefix(metrics, afunc, "My function 1")
    | :? (string -> string) -> WrapFunctionWithPrefix(metrics, afunc, "My function 2")
    | _ -> failwith "Unknown function def"

Is there any way of pattern matching based on the function signature in F#?

Any help appreciated.

Billy

like image 499
bstack Avatar asked Apr 14 '15 12:04

bstack


1 Answers

Would it be possible to declare the cases as a DU?

type MyFunctions =
| Intish of int -> int
| Stringish of string -> string
like image 189
Daniel Fabian Avatar answered Sep 28 '22 04:09

Daniel Fabian