4

What is the differences between Ocaml type casting / conversion methods below?

let a = (float) b ;;

And

let a = float_of_int b ;;

(Consider a is a float and b is an integer.) Is there any advantage one over another? or are they same?

Darshana
  • 130
  • 1
  • 8

3 Answers3

13

There's no general type casting mechanism in OCaml. There happens to be a function named float that does the same thing as float_of_int. You can use either one, with or without the extra parentheses.

$ ocaml
        OCaml version 4.03.0

# float 3;;
- : float = 3.
# float_of_int 3;;
- : float = 3.
# (float) 3;;
- : float = 3.
# (float_of_int) 3;;
- : float = 3.

But there's no function named (say) int:

# int 3.1;;
Error: Unbound value int
# (int) 3.0;;
Error: Unbound value int

Type casting as in C (and related languages) wouldn't really be compatible with the strong type system of OCaml.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • Interesting how `(float)` doesn't result in the (erroneous) application of `float` to 0 arguments (erroneous because it expects an `int` argument). I should revisit the syntax.. – Hunan Rostomyan Aug 14 '16 at 15:31
  • 3
    OCaml functions are first class values, and you can always use them with fewer arguments than they take, including 0. Parenthesizing any expression is allowed, and a function name (being a first class value) is an expression. – Jeffrey Scofield Aug 14 '16 at 15:35
  • 1
    @HunanRostomyan The function call syntax in OCaml is simply `expression expression` where the first expression needs to evaluate to a function. Note that no parentheses are part of that syntax. Parentheses are simply used to group expressions and can be added around any expression (like you could write `(1) + (2)` if you wanted to). – sepp2k Aug 16 '16 at 15:25
8

According to their definitions in the pervasives module, float and float_of_int are two identical functions:

external float : int -> float = "%floatofint"
external float_of_int : int -> float = "%floatofint"

Furthermore, the style of writing (float) b is not type casting. It is still a function application. The parentheses used here don't mean type casting, but they can be considered as parts of the expression.

For example, the following three expressions are the same:

let a = (float) b;;

let a = (float b);;

let a = float b;;
Trung Ta
  • 1,582
  • 1
  • 16
  • 25
4
let a = (float) b 

is interpreted by the syntax rules as

let a = float b 

where float is a function of type int -> float and happens to be the same function as float_of_int. This is not a type conversion as the C-like statement

double a = (float)b;

which has no equivalent in OCaml.

mookid
  • 1,132
  • 11
  • 19