Is there a library function available in Haskell to compose a function with itself n times?
For example I have this function:
func :: a ->
The iterate
solution is fine, or you might like this one: the composition of n
copies of f
is foldr (.) id (replicate n f)
.
Here's a version that has complexity O(log n) instead of O(n) (to build the function, not to apply it):
composeN 0 f = id
composeN n f
| even n = g
| odd n = f . g
where g = g' . g'
g' = composeN (n `div` 2) f
I do not know why you say that iterate
is not appropriate. It is perfectly suitable for this purpose. (!! n) . iterate func
is the composition of n
copies of func
.
(Someone had posted an answer similar to the above code, but he/she seems to have deleted it.)
(\n -> appEndo . mconcat . replicate n . Endo) n f x
\n -> appEndo . foldMap Endo . replicate n
iterate (f .) id !! n
or
iterate (f .) f !! (n-1)
depending on if n == 0
is allowed.