N
N
Nevars2014-09-28 23:20:59
Haskell
Nevars, 2014-09-28 23:20:59

How to compose a function on itself?

Hello. There is some function:
go f = execute f n
Parameter f is some function (sin, cos etc.)
The execute function is structured like this:
execute f n = f . f . ... . f
As we can see, in the code the execute function is composed of the function f on itself n times.
How can this be described in Haskell?
Should be something like this:
execute sin 2 = sin(sin(sin 2))
Or with n == 4
execute sin 4 = sin(sin(sin(sin(sin 4))
n == 1
execute f 1 = f( f(1))
I.e. for a given parameter n function
PS I understand how to describe the composition of various functions, but I don't understand how to describe the composition of a function on itself n times.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ruchkin, 2014-09-29
@Nevars

The function is applied n + 1 times to n. To do this, we need to collapse the list of n + 1 functions f using composition, and then apply it to the argument. Let's also add fromIntegral, since in the examples you have sines that need a floating point number, and n is an integer (the function can only be applied an integer number of times).
where replicate (succ n) f is a list of n + 1 f functions, foldr1 (.) is list folding
by composition , i.e. So:
where ($) is the application function, i.e. f$x = fx

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question