Question

I'm trying to create a print statement that can print any type. I want to use type pattern matching to achieve this.

This doesn't work:

let print x = match x with | :? int -> printf "INT"; | _ -> None;;

I get the message:

let print x = match x with | :? int -> printf "INT"; | _ -> None;;
-----------------------------^^^^^^

stdin(47,30): error FS0008: This runtime coercion or type test from type 'a to int involves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed.

So, i can't do type matching on an int? What other types can i not do type matching on? What does it mean that further type annotations are needed?

Was it helpful?

Solution

Type test is performed on reference types only. Therefore:

let print x = 
    match box x with 
    | :? int -> printf "INT"
    | _ -> ()

or

let print (x: obj) = 
    match x with 
    | :? int -> printf "INT"
    | _ -> ()

would work.

Notice that your function doesn't type check since None is of option type which is different from unit type of printf "INT".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top