Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type conversion with float_of_int

Tags:

ocaml

I am starting with ocaml and tried:

float_of_int 8/2;;

I was expecting that it returns 4.0 because 8/2 is 4 but I get an error saying that:

Error: This expression has type float but an expression was expected of type
int 

What am I missing here?

like image 487
randominstanceOfLivingThing Avatar asked Apr 08 '26 09:04

randominstanceOfLivingThing


1 Answers

Your expression is parsed like this:

(float_of_int 8) / 2

So you're asking to divide a float using /, which applies to ints.

Function application (indicated in OCaml by putting two expressions side by side) has very high precedence, higher than all the binary infix operators. So you need to use parentheses.

It will work if you write:

float_of_int (8/2)
like image 171
Jeffrey Scofield Avatar answered Apr 10 '26 21:04

Jeffrey Scofield