sdgfsdh
sdgfsdh

Reputation: 37111

Why does type inference only work with a pipe here?

I have a piece of code like this:

let! deliveries = 
  async {
    match Option.map (fun x -> x.Address) maybeUser with
    | Some "" -> return []
    | Some address -> return! fetchDeliveries address
    | None -> return []
  }

The type inference on this fails at x.Address.

However, if I reorder the code with a pipe it works:

let! deliveries = 
  async {
    match maybeUser |> Option.map (fun x -> x.Address) with
    | Some "" -> return []
    | Some address -> return! fetchDeliveries address
    | None -> return []
  }

Why is this?

Upvotes: 3

Views: 59

Answers (1)

Chester Husk
Chester Husk

Reputation: 1473

This is because F#'s compiler is a single-pass, top-down, left-to-right compiler. So when typechecking a file, any type information from the left of an expression is able to be used to verify the right. The reason why the |> example works is because the left-hand side has a definite type (in this case some kind of User option type that you've defined, which tells Option.map that yes the item coming in is an User option, so the lambda function you pass in must be of type User -> something else, which of course it is.

Upvotes: 5

Related Questions