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:
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").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With