Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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!

like image 263
phxxx Avatar asked Sep 14 '11 21:09

phxxx


People also ask

How do you repeat a function with n times?

The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.

How do I call a function twice in Python?

Use the oml. index_apply function to run a Python function multiple times in Python engines spawned by the database environment. The times argument is an int that specifies the number of times to run the func function. The func argument is the function to run.

What is replicate Haskell?

replicate takes an Int and a value, and returns a list that has several repetitions of the same element.


1 Answers

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.

like image 179
Thomas M. DuBuisson Avatar answered Oct 05 '22 01:10

Thomas M. DuBuisson