x^y
Toralf Wittner
wittner@uni-duesseldorf.de
Tue, 18 Dec 2001 17:43:33 +0100
Hello,
you can count me as a newbie in functional programming. I'm attempting to
define a function that computes the value of x^y for whole numbers. Intuively
(all efficiency considerations aside) I would start with something like this:
power x y
| x == 0 = 0
| y == 0 = 1
| y > 0 = x * power x (y-1)
| y < 0 = 1 / fromInteger x * power x (y+1)
One recognizes that the function returns either an integer value if y > 0 or
a float value if y < 0. Therefore I can't write a signature like
pow :: Integer -> Integer -> Integer nor can I do
pow :: Integer -> Integer -> Double. If I would use Python I could write
something like this:
def power(m, n):
if m == 0: return 0
if n == 0: return 1
if n > 0: return m * power(m, (n-1))
if n < 0: return (1 / float(m)) * power(m, (n+1))
How then would I write this function in Haskell (concerning types)?
Thanks in advance! Kind regards,
Toralf