Type inference
How to avoid getting distracted by complex type syntax
As you have already seen, F# uses a technique called "type inference" to greatly reduce the number of type annotations that need to be explicitly specified in normal code. And even when types do need to be specified, the syntax is less longwinded compared to C#.
To see this, here are some C# methods that wrap two standard LINQ functions. The implementations are trivial, but the method signatures are extremely complex:
public IEnumerable<TSource> Where<TSource>(
IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
{
//use the standard LINQ implementation
return source.Where(predicate);
}
public IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
{
//use the standard LINQ implementation
return source.GroupBy(keySelector);
}And here are the exact F# equivalents, showing that no type annotations are needed at all!
You might notice that the standard F# implementations for "filter" and "groupBy" have the parameters in exactly the opposite order from the LINQ implementations used in C#. The "source" parameter is placed last, rather than first. There is a reason for this, which will be explained in the thinking functionally series.
The type inference algorithm is excellent at gathering information from many sources to determine the types. In the following example, it correctly deduces that the list value is a list of strings.
And in this example, it correctly deduces that the sumLengths function takes a list of strings and returns an int.
Last updated
Was this helpful?