[Haskell-beginners] Does this function already exist in one of
the standard modules?
daniel.is.fischer at web.de
Sat Aug 8 16:54:15 EDT 2009
Am Samstag 08 August 2009 22:01:34 schrieb I. J. Kennedy:
> Does this function already exist in one of the standard modules?
> It computes f(f(f(...f(x))). I suspect it is a common function, but I
> can't find it, even using Hoogle.
> applyMany :: Int -> (a -> a) -> a -> a
> applyMany 0 f x = x
> applyMany n f x = applyMany (n-1) f (f x)
Not directly, I think.
But we have
iterate :: (a -> a) -> a -> [a]
iterate f x = x:iterate f (f x)
so applyMany n f x = iterate f x !! n
Most of the time you either need different numbers of iterations for the same starting
value, then iterate is what you want, or the same number of iterations for different
values, then you use something like
let g = foldl (.) id (replicate n f) in ...
More information about the Beginners