I am learning F# and have some experience with Python. I really like Python function decorators; I was just wondering if we have anything similar to it in F#?
			
			1050 次
		
1 回答
            10        
        
		
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 的装饰器。例如,这个 Python 示例
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"
可以翻译成F#如下
let makebold fn = 
    fun () -> "<b>" + fn() + "</b>"
let makeitalic fn =
    fun () -> "<i>" + fn() + "</i>"
let hello =
    let hello = fun () -> "hello world"
    (makebold << makeitalic) hello
于 2012-10-14T09:16:40.900   回答