5
我正在学习F#并且有一些Python的使用经验。我非常喜欢Python函数装饰器;我只是想知道在F#中是否有类似的东西?F#编程语言中有没有类似Python函数装饰器的东西?
我正在学习F#并且有一些Python的使用经验。我非常喜欢Python函数装饰器;我只是想知道在F#中是否有类似的东西?F#编程语言中有没有类似Python函数装饰器的东西?
F#中的函数装饰器没有语法糖。
对于类型,您可以使用StructuredFormatDisplay
属性来自定义printf内容。下面是从F# 3.0 Sample Pack一个例子:
[<StructuredFormatDisplayAttribute("MyType is {Contents}")>]
type C(elems: int list) =
member x.Contents = elems
let printfnSample() =
printfn "%A" (C [1..4])
// MyType is [1; 2; 3; 4]
对于函数,可以很容易地使用函数组合物表达Python's decorators。例如,this Python example
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
可以如下
let makebold fn =
fun() -> "<b>" + fn() + "</b>"
let makeitalic fn =
fun() -> "<i>" + fn() + "</i>"
let hello =
let hello = fun() -> "hello world"
(makebold << makeitalic) hello
参见被转换为F#[装饰图案的功能性等价物?](http://stackoverflow.com/questions/7064389/functional换算-的-装饰图案)。 – nneonneo