Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Generic Programming - Using members

Suppose I have a family of types which support a given member function, like the Property member below:

type FooA = {...} with

    member this.Property = ...

type FooB = {...} with

    member this.Property = ...

Suppose the member Property returns an integer for each of the the above types. Now, I wan to write a generic function that could do the following:

let sum (a: 'T) (b: 'U) = a.Property + b.Property

I am used to write the following in C++:

template<typename T, typename U>
int sum(T a, U b)
{
    return a.Property + b.Property;
}

How would be an equivalent implementation in F#?

like image 869
Allan Avatar asked Dec 22 '22 23:12

Allan


1 Answers

It is possible to do this in F#, but it isn't idiomatic:

let inline sum a b = (^T : (member Property : int) a) + (^U : (member Property : int) b)

In general, .NET generics are very different from C++ templates, so it's probably worth learning about their differences first before trying to emulate C++ in F#. The general .NET philosophy is that operations are defined by nominal types rather than structural types. In your example you could define an interface exposing a Property property, which your two classes implement, and then your sum function would take instances of that interface.

See http://msdn.microsoft.com/en-us/library/dd233215.aspx for more information on F# generics; for a brief comparison of .NET generics versus C++ templates see http://blogs.msdn.com/b/branbray/archive/2003/11/19/51023.aspx (or really anything that comes up when you Google ".NET generics C++ templates").

like image 117
kvb Avatar answered Dec 26 '22 00:12

kvb