Search code examples
argumentssmlcurryingsmlnjml

How to declare inputs of a curried function as real in sml?


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?


Solution

  • 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.