6

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

pad
  • 41,040
  • 7
  • 92
  • 166
akrohit
  • 1,023
  • 1
  • 10
  • 14
  • 2
    See also [Functional equivalent of decorator pattern?](http://stackoverflow.com/questions/7064389/functional-equivalent-of-decorator-pattern). – nneonneo Oct 14 '12 at 08:38

1 Answers1

10

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
Community
  • 1
  • 1
pad
  • 41,040
  • 7
  • 92
  • 166