smlmlmosml

Writing power function in Standard ML with a predefined compound function


Having trouble writing a power function inStandard Ml. Im trying to write a function called exp of type int -> int -> int.

The application exp b e, for non-negative e, should return b^e.

For example, exp 3 2 should return 9. exp must be implemented with the function compound provided below. exp should not directly calls itself. Here is the compound function, it takes in a value n, a function, and a value x. All it does is it applies the function to the value x n number of times.

fun compound 0 f x = x 
  | compound n f x = compound (n-1) f (f x);

Im having trouble figuring out how to write this function without recursion, and with the restraint of having to use a function that only can use a function with one parameter. Anyone have any ideas of where to start with this?

This is what I have:

fun exp b 0 = 1  
  | exp b e = (compound e (fn x => x*x) b)  

I know that this doesn't work, since if i put in 2^5 it will do: 2*2, 4*4, 16*16 etc.


Solution

  • You could just do this instead I believe

      fun exp 0 0 = 1
      | exp b 0 = 1
      | exp b e = (compound (e - 1) (fn x => b * x ) b);