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
nTimesunTimes'always get the same result? - Will it be
nTimes'faster?