Library function to compose a function with itself n times

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.)


\xs n -> iterate func xs !! n

(xs is the initial value, n is the number of times to apply func)

I don't know why, but I feel like iterate is something people aren't consistently exposed to when learning Haskell.

If you don't like !! then you could use zip and lookup as an alternative. (some people/groups/tools don't like functions that call "error" in certain cases, I'm not claiming lookup is any better in these cases)

lookup n . zip [0..] . iterate func

EDIT: Ok, so I deleted then undeleted because I agree with the other answerer - you shouldn't discount use of iterate just because it gives you more than you need.


The iterate solution is fine, or you might like this one: the composition of n copies of f is foldr (.) id (replicate n f).

Tags:

Haskell