08.08.07

Exercise 9.8

Posted in Uncategorized at 11:18 pm by admin

power :: (a -> a) -> Int -> a -> a
power f 0 = (\x -> x)
power f n = (\x -> f (power f (n-1) x))

Since the function is called power, there is one obvious application that springs to mind, i.e. raising to a power:

raise :: Int -> Int -> Int
raise x y = power (*x) y 1

2 Comments »

  1. Markus Dittrich said,

    August 31, 2008 at 2:14 pm

    The following is a possible definition for power using
    higher-order functions:

    power :: ( a -> a ) -> Int -> a -> a
    power f n = let funcList = replicate n f
                in (foldr (.) id funcList)
  2. Ricky Liu said,

    March 8, 2014 at 1:46 am

    It can be simplified to:

    power f n = foldr (.) id (replicate n f)

Leave a Comment