My Technical Notes

Saturday, 26 July 2014

F# type with a member constraint

F# is perhaps the only language which supports member constraints. Here is an example of a type (class) which accepts an object satisfying a constraint and then calls a property (Property1):

type Class6<'T when 'T : (member Property1 : int)>(x: 'T) =
    member inline __.Property1 = (^T : (member Property1 : int) (x))
Instead of wrapping the object in another type, we could instead have a static class which has a bunch of static functions which invoke the methods we want to wrap:

type Class7 =
    static member inline Property1 (sample: ^T) = 
        (^T : (member Property1 : int) (sample))
Note that the best documentation is the MSDN Member Constraints page.

No comments: