15

I was implementing a C# interface in F# that looked something like:

public interface IThings
{
    Stream ThingsInAStream()
}

My implementation looked something like:

type FSharpThings() = 
    interface IThings with
       member this.ThingsInAStream() = 
           let ms = new MemoryStream()
           // add things to stream
           ms

Now I get the message:

The expression was expected to have type 
  Stream
but here has type
  MemoryStream

I don't understand MemoryStream IS a Stream I know that I can cast it to as stream like:

ms :> Stream

Same goes for [|"string"|] and IEnumerable<string> it implements the interface and I can explicitly cast to it BUT it doesn't work automatically.

Why does this work?

let things:(IEnumerable<'a> -> 'a) = (fun f -> f.First())

let thing= things([|"";""|])

This is also automatic upcasting!

0

2 Answers 2

13

I think the answer from Nicolas is generally right. Allowing automatic up-casting everywhere in the language would cause problems for type inference.

In principle, the compiler could try looking for a common base type of the types returned in different branches, but this is not as easy as it sounds:

  • First, should it return the most specific type or some other type? (The compiler could find the most specific, but perhaps you actually want to return something a bit more general than what could be inferred from your code - so specifying that explicitly is useful.)

  • Second, things get difficult with interfaces. Imagine that two branches return two different classes both implementing interfaces IA and IB. How does the compiler decide whether the return type should be IA or IB, or perhaps obj? (This is a big problem, because it significantly affects how the code can be used!) See this snippet for more details.

However, there is one place where this is not a problem and F# compiler allows it. That is, when passing argument to a function or a method - in this case, the compiler knows what the desired type is and so it only needs to check that the upcast is allowed; it does not need to infer what upcast to insert. As a result, the type inference is not affected and so the compiler can insert an upcast. That is why the following works:

// The example from the question
let first (items:seq<'a>) = items |> Seq.head
let thing = first [|"";""|]

// Even simpler example - passing string as object
let foo (a:obj) = a 
foo "123"

Here, the argument is array<string> and the function expects seq<string>. The compiler knows what upcast to insert (because it knows the target type) and so it does that.

6
  • One could say in that case the compiler knows the return type in practice as well, since appending :> _ would make it work. Still a guess though, and the rule looks like there is no upcast based on a guess.
    – nicolas
    Commented May 29, 2013 at 13:44
  • @nicolas Do you mean in the case with IA and IB interfaces? If you add :> _ you get an error "error FS0013: The static coercion from type First to 'a involves an indeterminate type based on information prior to this program point. Static coercions are not allowed on some types. Further type annotations are needed." Commented May 29, 2013 at 13:48
  • not if you write "let test : IA" first, which might be closer to what is here : we know the return type should be Stream.
    – nicolas
    Commented May 29, 2013 at 13:51
  • @nicolas True. If you always specify type explicitly somewhere than it will work (just like when calling a function or a method - at least method that is not overloaded). But again - I think it would make the system more complex (e.g. perhaps you'd need some priority to make sure explicit annotations are always preferred in the constraint solving) Commented May 29, 2013 at 13:54
  • 2
    As a minor additional note, there are a few other places where something that looks like upcasting takes place. For instance, let o:obj = first [1; "1"]. List and array literals have some extra logic for unifying the types of their constituents.
    – kvb
    Commented May 29, 2013 at 14:59
11

This is the counterparty of having a powerful type inference mechanism : By having everything explicit, it is easier for the compiler to reason about what is true or not.

It feels strange at first, as we are relying so much on those conversions in other relaxed langage.

But practically it turns out to be a strength overall, and allow both the type inference mentioned, as well as promotes good programming practices like programing to the interface VS the concrete implementation.

One useful construct in cases, where it feels plain superfluous, is to add the cast

//The cast will be determined by the compiler, because of _
result :> _
14
  • 2
    Doesn't programming against the interface as you say result in code littered with :> _ ? Since every function that returns an interface in fact returns another object that implements that interface. I don't think it promotes programming to the interface at all since the type gets infered it'll infer the concrete type instead of the the interface.
    – albertjan
    Commented May 29, 2013 at 10:24
  • 1
    Could you elaborate a bit further? I've read your answer a couple times now and it'll probably make sense to people familiar with f# but it doesn't make sense to me. Somehow it feels like the type inference mechanism only works one way.
    – albertjan
    Commented May 29, 2013 at 10:35
  • 2
    Could you cite an example of where inferring a "greatest common" base type among branches of an expression actually undermines other features of F#'s type inference? My feeling was always that such a feature was not implemented due to philosophy or complexity (time), not technical. Commented May 29, 2013 at 12:16
  • 4
    To give an example where things would not work nicely, imagine that two branches return two different classes both implementing interfaces IA and IB. How does the compiler decide whether the return type should be IA or IB, or perhaps obj? (This is a big problem, because it significantly affects how the code can be used!) Commented May 29, 2013 at 13:12
  • 3
    A nice alternative to 'result :> _' is 'upcast result'. Commented Jun 25, 2013 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.