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#?
It is possible to do this in F#, but it isn’t idiomatic:
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
Propertyproperty, which your two classes implement, and then yoursumfunction 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”).