[Haskell-cafe] Repeated function application

Ben Butler-Cole ben at bridesmere.com
Thu Feb 21 10:58:13 EST 2008


I was surprised to be unable to find anything like this in the standard libraries:

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

Am I missing something more general which would allow me to repeatedly apply a function to an input? Or is this not useful?

I thought this looked a bit like a fold, so I tried expressing it like this:

times f n x = foldl (flip ($)) x (replicate n f)

... which horrifies me, but I can't help feeling that there must be a way to get rid of the explicit recursion.

How would you implement times?


More information about the Haskell-Cafe mailing list