how to write a power function which makes use of the following facts: To raise x to a power n (where n is a positive whole number), if n is even, you can find the nth power of x by squaring half that power. For example, x^12 is x^6 * x^6. For odd powers, just subtract one from the power, and multiply the result for the smaller power by x. for example, x^13 is x * x^12, which is x * x^6 * x^6. Recursively, any power can be found with less work than multiplying x by itself the number of times indicated.
I came up with this
power x n
| n == 0 = 1
| x == 0 = 0
| even n = ( power x (n / 2) ) * ( power x (n / 2) )
| odd n = x * ( power x ((n - 1) / 2)) * ( power x ((n - 1) / 2) )
but I get an error saying ERROR – Unresolved overloading
* Type : (Integral a, Fractional a) => Integer
* Expression : power 2 2
Just a remark now that your code is running: Haskell doesn’t automatically memoize functions, so you’re calculating the recursive calls to
powertwice in the last two lines. I would recommend to introduce a simple functionsqr k = k * kand to use it. There are several ways: a separate function; awhereclause; andlet.I would prefer
let:As you can see pattern matching deals with the first two cases. Then
letdefines some useful expressions, which can be used later inin. Note that for odd numbers,(n-1) `div` 2gives the same result asn `div` 2, so we can unify both cases.