F # Creating a custom attribute for an expression

In F #, how can I create a custom attribute to apply to expressions? I have searched for resources all over the place but found nothing.

As an example, an Attribute [<Entrypoint>]

can be applied to some expression, and hence the compiler can infer that the expression must have a type array string -> int

.

How do I create a custom attribute for the mail merge to work?

+5


source to share


1 answer


To create a custom attribute, simply declare a class that inherits from System.Attribute

:

type MyAttribute() = inherit System.Attribute()

[<My>]
let f x = x+1

      

As you can see, the "Attribute" suffix can be omitted when applying the attribute to code units. Optionally, you can specify your attribute or parameters:

type MyAttribute( x: string ) =
    inherit System.Attribute()
    member val Y: int = 0 with get, set

[<My("abc", Y=42)>]
let f x = x+1

      

At runtime, you can check types, methods, and other units of code to see which attributes are applied to them and get their data:



[<My("abc", Y=42)>]
type SomeType = A of string

for a in typeof<SomeType>.GetCustomAttributes( typeof<MyAttribute>, true ) do 
    let my = a :?> MyAttribute
    printfn "My.Y=%d" my.Y

// Output:
> My.Y=42

      

Here is a tutorial explaining custom attributes in more detail.

However, you cannot use custom attributes to enforce compile-time behavior. EntryPointAttribute

is special, that is, the F # compiler is aware of its existence and gives it a special approach. In F #, there are some other special attributes - for example NoComparisonAttribute

, CompilationRepresentationAttribute

etc. - but you cannot tell the compiler about special handling for attributes you created yourself.

If you describe your big goal (that is, what you are trying to achieve), I'm sure we can find a better solution.

+10


source







All Articles