开发者

How to call the same function 'n' times? [duplicate]

This question already has answers here: Closed 11 years ago. 开发者_如何转开发

Possible Duplicate:

Library function to compose a function with itself n times

I need a function to call another function n number of times.

so it would look something like this f n = g(g(g(g(l)))) where n equals to the number of function g nested.

how should I go about this? thanks!


iterate is a common solution:

> :t iterate
iterate :: (a -> a) -> a -> [a]

So, given a function with a domain the same as its range, a -> a, and an initial input a, produce an infinite list of results in the form:

iterate f a --> [a, f(a), f(f(a)), ...]

And you can access the nth element of the list using !!:

iterate f a !! n

NB iterate f a !! 0 == a.


This is a function that I use often at the ghci prompt. There are a few ways to write it, none of which I am particularly fond of, but they are all reasonably clean:

fpow n f x = iterate f x !! n

fpow n f = foldr (.) id $ replicate n f

fpow n = foldr (.) id . replicate n   -- just eta the above

fpow 0 f = id
fpow n f = f . fpow (n-1) f

The middle two appeal to me because my brain has chunked foldr (.) id to mean "compose a list of functions".

I kinda just wish it were in the prelude :-).


f 0 = l
f n = g (f (n-1))

But more functional would be:

f 0 l = l
f n l = g (f (n-1) l)

This could also be done with folds or morfisms, but this is easier to understand.

For example here's using a hylomorphism, but it doesn't make it clearer really:

f g l = hylo l (.) (\n -> (g, n-1)) (==0)

It says some thing like compose (.) g(l) until n==0


Can be done using fold:

applyNTimes :: Int -> (a -> a) -> a -> a
applyNTimes n f val = foldl (\s e -> e s) val [f | x <- [1..n]]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜