Type inference in F# works left-to-right through an expression; for example

1
2
3
4
5
6
7
8
 

let s = seq { yield "foo"; }

let s2 = s |> Seq.sort_by (fun x -> x.Length) // compiles

//let s2 = Seq.sort_by (fun x -> x.Length) s // does not

In the first one, we already know that the elements of 's' are type 'string' by the time we reach the lambda body and "x.Length". In the second one, we don't. This is one of the things that makes the pipelining style so attractive.

By on 4/8/2009 6:15 AM ()

Type inference in F# works left-to-right through an expression;

Is this because the postfix operation is used?

It seems like inference works (almost) perfectly until I start mixing in a.[i] and obj.doMethod

Out of curiosity, is there a reason why the compiler can't handle this automatically? It seems to me like all operations could be transformed to left-right in the compiler.

By on 4/9/2009 8:04 AM ()

I don't know; I haven't thought about this deeply (I'm sure Don has). My guess is there are trade-offs, in that if you make the type inference algorithm smarter, you risk

  • having the algorithm take longer (e.g. programs that take forever to compile before finally failing)
  • accidentally making the type-inferencer Turing-complete (don't want to go there)
  • having error messages become less predictable
  • having a more complex mechanism makes it harder for humans to understand/simulate/predict

Though the type inferencer is pretty powerful today, the three-line summary I gave in a previous message on this thread can often adequately explain its behavior in 95% of situations.

(And yes, as it stands, it feels like perhaps > 80% of the 'need to add an annotation' errors come from "o.M" where the type of "o" didn't already flow into this expression from the left; this is one of the few expressions in the language that cannot "float a new constraint" to be solved later, as there is no generic type constraint in .Net that means "forall types 'a where 'a has a method or property named M constrained by this signature".)

By on 4/9/2009 9:17 AM ()

Thanks. And good pointer about pipelining style there.

By on 4/8/2009 7:47 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper