Search code examples
typesocamlvariantalgebraic-data-types

Int of Int in Ocaml types


In an assignment, I have two user-defined types. Type a uses INT of int and type b uses Int of int. As far as I understand, this means that both these types can accept an int as part of that type. Is there any way to convert between types a and b? I've tried typecasting like

let typeA = INT 5
let typeB = Int 5
let cast = INT(typeB)

but that throws a type mismatch error.


Solution

  • OCaml is a strongly typed language, so there is no way in general to "type cast" from one type to another.

    You can write a function that converts one type to another, however. For example, there is a built-in function named float_of_int that converts a float to an int. There is also int_of_float (which throws away any fractional part of the float value).

    You can easily write functions in a similar spirit to convert between your two types.

    Here's some code that contains all the ideas you need (I think):

    type mytype = MyConstructor of int
    
    let increment (MyConstructor x) = MyConstructor (x + 1)