基于函数签名的模式匹配 [英] Pattern matching based on the function signature

查看:92
本文介绍了基于函数签名的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在F#中,你可以在函数签名上进行模式匹配。我想用一个函数来装饰许多函数,这个函数测量函数的执行并调用statsd。我现在使用的函数是:

$ p $ let WrapFunctionWithPrefix(Metric.Client.IRecorder,functionToWrap,prefix)= $ b $ (fun metrics - > functionToWrap)

正如您在上面看到的,前缀会有所不同,并且在我们的应用程序中,每个函数定义会有所不同。因此,不必每次都要传递度量前缀,如下所示:

  let WrapFunction metrics afunc = 

|匹配afunc :? (int - > int) - > WrapFunctionWithPrefix(metrics,afunc,My function 1)
| :? (字符串 - >字符串) - > WrapFunctionWithPrefix(metrics,afunc,My function 2)
| _ - > failwithUnknown function def

是否有任何基于F#中函数签名的模式匹配方式?



任何帮助表示赞赏。

解决方案

是否可以将案例声明为DU?

  type MyFunctions = 
|内在的int - > int
|字符串的字符串 - >字符串


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

解决方案

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

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

这篇关于基于函数签名的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆