Search code examples
smlsmlnjexponent

SML exponentiation of real with integer


I wrote a function that does exponentiation with a base, b and the exponent e as follows:

fun power b e = if e = 0 then 1 else b * power b (e-1);

obviously this is works on integers as shown by the output:

val power = fn : int -> int -> int

However, I want it to take a real for b and an integer for e. I tried to use the following:

fun power (b : real) (e : int) = if e = 0 then 1 else b * power b (e-1);

This gives me errors though. Any help is appreciated.


Solution

  • Got it for anyone else with the same issue in the future:

    You gotta force the function to return a real and return a real for the then case.

    fun power b e : real = if e = 0 then 1.0 else b * power b (e-1);
    

    returns:

    val power = fn : real -> int -> real