3

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.

Darrel Holt
  • 870
  • 1
  • 15
  • 39
  • 1
    by the way if you are really implementing this, you may want to use [exponentiation by squaring](http://en.wikipedia.org/wiki/Exponentiation_by_squaring), instead of linearly multiplying `b` `e` times – newacct Feb 29 '16 at 06:50

1 Answers1

5

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
Darrel Holt
  • 870
  • 1
  • 15
  • 39
  • 1
    `fun power b e = if e = 0 then 1.0 else b * power b (e-1);` also works. The `1.0` real literal is enough of a hint to SML's type inference. Given that, `:real` is superfluous (though harmless). – John Coleman Feb 27 '16 at 16:13