x^y
Till Doerges
till@doerges.net
Wed, 19 Dec 2001 10:13:45 +0100
On Tue, Dec 18, 2001 at 05:43:33PM +0100, Toralf Wittner wrote:
> 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)
Why did you put 'fromInteger' into the last line? If you get rid of
that, this will make your 'power' be accepted by the haskell-compiler
or -interpreter.
> 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.
No, you can't, and that's one of the reasons why type-classes where
introduced. You don't have to state the type of x and y
explicitely. Rather you can specify certain 'properties', i.e. y must
be a number, there must be an ordering relation and x must allow for the
representation of fractions.
--- snip ---
Main> :t power
power :: (Num a, Ord a, Fractional b) => b -> a -> b
Main> power 2 3
8.0
(113 reductions, 147 cells)
Main> power 2 (-1)
0.5
(70 reductions, 87 cells)
Main>
--- snap ---
> How then would I write this function in Haskell (concerning types)?
See above (the type signature was kindly provided by hugs ;-).
HTH -- Till
--
e-mail: reverse(net dot doerges at till) | ENCRYPTED |
pgp/gpg: keys via keyserver or my homepage | MAIL IS |
www: http://www.doerges.net | WELCOME! |