layout | title | description | nav | seriesId | seriesOrder | categories | ||
---|---|---|---|---|---|---|---|---|
post |
Type inference |
How to avoid getting distracted by complex type syntax |
why-use-fsharp |
Why use F#? |
8 |
|
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!
let Where source predicate =
//use the standard F# implementation
Seq.filter predicate source
let GroupBy source keySelector =
//use the standard F# implementation
Seq.groupBy keySelector source
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.
let i = 1
let s = "hello"
let tuple = s,i // pack into tuple
let s2,i2 = tuple // unpack
let list = [s2] // type is string list
And in this example, it correctly deduces that the sumLengths
function takes a list of strings and returns an int.
let sumLengths strList =
strList |> List.map String.length |> List.sum
// function type is: string list -> int