Konata
Konata

Reputation: 81

Difference between "as" and a colon to specify type?

I originally thought "as" and the colon operator meant the exact same thing, to specify a type for a value or function. But I actually found an inconsistency:

type Uppercase = string -> string
let uppercase:Uppercase = fun n ->
    //code

This works fine. But then if I change the colon to "as"

type Uppercase = string -> string
let uppercase as Uppercase = fun n ->
    //code

It breaks, saying it doesn't know what type "n" is. Of course, I can just fix that by doing

type Uppercase = string -> string
let uppercase as Uppercase = fun (n:string) ->
    //code

And it's happy again. So, my question is, why is "as" different from colon and why does it seem F# can't do type inference when using "as"? Thanks.

Upvotes: 2

Views: 95

Answers (1)

Lee
Lee

Reputation: 144136

as is used to name the result of a pattern match e.g.

let (a,b) as t = (1,2)

will bind a to 1, b to 2 and t to the whole pair. Therefore

let uppercase as Uppercase = fun n -> ...

binds the names uppercase and Uppercase to the function. In this function, the type of n is not specified so you get the type error.

as is therefore quite different from an explicit type declaration and can't be used interchangeably.

Upvotes: 5

Related Questions