Type conversion

Hi there, we know that OCaml supports module type. So we may get a integral of value with different type (like A.t and B.t even though the t in each module is defined as int).

My question is, how can we convert a variable from one type to another? Say we have module A and B and I want to transform a variable from type A.operand to B.operand.

open Core

module A = struct
  type operand = 
  | Imm of Int32.t
end

module B = struct
  type operand = 
  | Imm of Int32.t
end

module C = struct
  let transform (op : A.operand) : B.operand = match op with
  | Imm i -> i
end

We know that both A and B has type operand formed of Int32.t. However, the transform function will fail to compile with error

16 |   | Imm i -> i
                  ^
Error: This expression has type int32 but an expression was expected of type B.operand

There are some type conversion functions like string_of_int. But how can we define a custom conversion function?

You simply need to construct a value of type B.operand instead of Int32.t :

let transform (Imm i : A.operand) : B.operand = Imm i

Or

let transform (A.Imm i) = B.Imm i
1 Like

If you have the same representation for types in both modules, you can share a common type in the implementation, but hide it in the interface. Conversion becomes free then.

2 Likes

Thank you for your answer, what does let transform = Fun.id mean in the left side panel?

ohhhh, never mind, it is identical function.