Reputation: 22133
In C#, mostly every expression has a type, with some exceptions:
and perhaps others I'm not aware of. These make type inference impossible, for instance this is illegal:
var a = null;
F# is a language where everything is an expression: does any expression in F# not have a type? (I just typed let a = null
in the interactive and it returned that a
was of generic type a'
, but I'm not sure if that means the F# null
is a generic type or typeless.)
Upvotes: 4
Views: 263
Reputation: 29100
F# doesn't have the same limitation as C# in terms of types for anonymous methods/lambdas, because it handles anonymous functions in a different way and infers a general type for them using Hindley-Milner type inference.
So translating Eric Lippert's example to F# (using fsi to get immediate feedback):
> let f = fun i -> i;;
val f : 'a -> 'a
We get the generic type 'a - >'a
inferred for f
.
However there are some situations the type inference system can't handle without knowing the type in advance, which probably provide the closest analogue to the C# typeless expressions. For example:
> let f i = i.Value;;
let f i = i.Value;;
----------^^^^^^^
stdin(18,11): error FS0072: Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved.
In other words the expression i.Value
doesn't make sense if we don't know the type of i
, because the compiler can't tell which Value
property we are using and doesn't have any way to abstract over it in the type.
On the other hand if we constrain i
so that the compiler does know what the Value
property is, all is fine:
> let f (i : 'a option) = i.Value;;
val f : 'a option -> 'a
Upvotes: 2