1
votes

I'm a newbie on OCaml and I was trying to make a tail recursion function what calculates the factorial of a float. Here's what I've done:

let factorial num =
let rec aux i f =
    if i=num then f
    else aux (i+.1.) (float f*.(i+.1.))
in aux 0. 1.;;

It gives me this error: This expression has type float but an expression was expected of type int.

I don't know how to fix that 'cause I can't find where's the error.

1
Why do you use float f in the 4th line?Basile Starynkevitch

1 Answers

3
votes

float is a function that takes an int and returns a float.

# float;;
- : int -> float = <fun>

Your expression float f is therefore forcing f to be an int, which is forcing aux to take an int as the final argument, which is then breaking because the argument to aux from (float f*.(i+.1.)) is a float.

It looks like you want everything to be a float, so you just need to drop the call to float.

# let factorial num =
    let rec aux i f =
      if i=num then f
      else aux (i+.1.) (f*.(i+.1.))
   in aux 0. 1.;;
val factorial : float -> float = <fun>

# factorial 4.0;;
- : float = 24.