Matching patterns based on function signature

In F #, you can match a pattern by function signature. I want to decorate a number of functions with a function that measures the execution of a function and is called in statsd. My current function:

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 change, and in our application this will depend on the definition of the function. So instead of passing 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 a way to match patterns based on function signature in F #?

Any help was appreciated.

Billy

+6
source share
2 answers

Can things be declared as DU?

 type MyFunctions = | Intish of int -> int | Stringish of string -> string 
+7
source
 let WrapFunction metrics afunc = match box afunc with | :? (int -> int) -> WrapFunctionWithPrefix(metrics, afunc, "My function 1") | :? (string -> string) -> WrapFunctionWithPrefix(metrics, afunc, "My function 2") | _ -> failwith "Unknown function def" 

will work for your pattern matching. Usually, before putting them, you should box unknown types, like :? I don’t like to use value types.

I'm not quite sure how your use statement will interact with the function you are returning. I think that it will have the metrics and return the function immediately, which is probably not the way you want.

+3
source

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


All Articles