1

Here is my code for a curried factorial function I want the output as real

fun pow(x:real) (n:real)= if (n=0.0) then 1.0 else x:real*pow(x:real) (n-1:real) ;

But my syntax is really really wrong how do I fix this?

  • The following Q&A: [Why can't I compare reals in Standard ML?](https://stackoverflow.com/questions/41394992/why-cant-i-compare-reals-in-standard-ml) has the `real` factorial function as its example (although rewritten into pattern matching). But I admit ruakh's `real` solution below which avoids the comparison is pretty neat, too. – sshine Feb 24 '20 at 09:59
  • Why not use the built-in `Math.pow : real * real -> real`, though? – sshine Feb 24 '20 at 15:13

1 Answers1

1

I think what you want is:

fun pow x n =
  if n = 0
  then 1.0
  else x * pow x (n - 1)

or, if you want to be a bit more explicit about the types:

fun pow (x : real) (n : int) : real =
  if n = 0
  then 1.0
  else x * pow x (n - 1)

That is:

  • I think you want n to be of type int, not type real. (Your approach only makes sense if n is a nonnegative integer, since otherwise the recursion would just go forever.)
  • You don't need so many :real-s everywhere; they don't add anything, because the compiler can infer the types.
ruakh
  • 175,680
  • 26
  • 273
  • 307