sunnn
sunnn

Reputation: 13

OCaml how to convert a polymorphic number to a float?

I want to calculate a polymorphic number. I know about float_of_int but I want to convert unknown types (int or float) to a float. So how can I convert a polymorphic number to a float?

Upvotes: 0

Views: 290

Answers (1)

Pierre G.
Pierre G.

Reputation: 4441

By making some assumptions on your use case:

type i_or_f = Int of int | Float of float;;
let conv x = match x with Int i -> float_of_int i | Float f -> f;;

i_or_f is the polymorphic type that is either an int or a float.

 utop # conv (Int 4);;
 - : float = 4.
 utop # conv (Float 4.);;
 - : float = 4.

Is it what you are thinking about ?

Upvotes: 1

Related Questions