0
votes

Please, could someone explain why here the function type is inferred to be string -> string?

let myFunc a:string = 
    match a with 
    | "A" -> 1
    | _ -> 0

This works fine when the argument is generic, but as soon as I add :string the type changes. Why?

Edit: I want to declare the argument type to be a string as I actually want to use String.ToUpper() for the match:

let myFunc a:string = 
    match a.ToUpper() with 
    | "A" -> 1
    | _ -> 0

A bit awkward solution would, be this

let myFunc a = 
    match a.ToString().ToUpper() with 
    | "A" -> 1
    | _ -> 0

But I really know it will be a string

1

1 Answers

6
votes

By writing :string at the end of the function signature, you're declaring the return type to be string. The type of a is inferred to be string because you pattern match it against strings, so the type of the function becomes string -> string.

Presumably you meant for the :string to apply to a, not the result of the function. To achieve this you'd need to surround it with parentheses like this:

let myFunc (a : string) =

Or if you want to specify both the argument type and the return type:

let myFunc (a : string) : bool =