Pattern matching based on the function signature

对着背影说爱祢 提交于 2019-12-23 09:17:31

问题


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


回答1:


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

type MyFunctions =
| Intish of int -> int
| Stringish of string -> string



回答2:


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 match. You normally end up having to box unknown types before trying to cast them, as :? doesn't like being used on value types.

I'm not totally sure how your using statement will interact with the function you return though. I think it will dispose metrics and return the function immediately, which is probably not what you want.



来源:https://stackoverflow.com/questions/29627950/pattern-matching-based-on-the-function-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!