a, we can create a function that ...">

Is it possible to "apply a function for n times" to perform using "squaring"?

Given a type function f :: a -> a, we can create a function that applies fto ntimes:

nTimes :: Int -> (a -> a) -> (a -> a)
nTimes 0 _ = id
nTimes 1 f = f
nTimes n f = f . nTimes (n-1) f

I can use the squaring method to implement another function nTimes:

nTimes' :: Int -> (a -> a) -> (a -> a)
nTimes' = nTimes'' id
    where
        nTimes'' acc n f
            | n == 0    = acc
            | even n    = nTimes'' acc (n `div` 2) (f . f)
            | otherwise = nTimes'' (acc . f) (n-1) f

My question is:

  • Do nTimesu nTimes'always get the same result?
  • Will it be nTimes'faster?
+4
source share
3 answers

, , ntimes' . , x * x , f . f , f. , , f , - . ntimes (n-1) f x , , , f ntimes (n-2) f x ..

EDIT: , , memoization, .. f . f memo (f . f) memo-combinator, . , ntimes' . .

+8

, * . .

"" - , . , *, . , ., .

, Ørjan Johansen, *, . - , .

, nTimes', , f n . , , ..

+6

nTimes nTimes ?

. ( , ).

nTimes ?

, . f , .

f , f f, .

+4

All Articles