Is there anything similar to Python function decorators in F# programming language?

decorator, f#, python

Solution

There is no syntactic sugar for function decorators in F#.

For types, you can use `StructuredFormatDisplay` attribute to customize printf contents. Here is an example from 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]

For functions, you can easily express Python's decorators using function composition. For example, 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"

can be translated to F# as follows

let makebold fn = 
    fun () -> "<b>" + fn() + "</b>"

let makeitalic fn =
    fun () -> "<i>" + fn() + "</i>"

let hello =
    let hello = fun () -> "hello world"
    (makebold << makeitalic) hello

Problem

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#?

Original source

Related problems