Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 810
akrohit Avatar asked Oct 14 '12 08:10

akrohit


Video Answer


1 Answers

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
like image 50
pad Avatar answered Oct 08 '22 10:10

pad