Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Library function to compose a function with itself n times

Tags:

haskell

Is there a library function available in Haskell to compose a function with itself n times?

For example I have this function:

func :: a -> a 

and I want to do this:

func . func . func . func . func . func , ...  

(up to n times, where n is only known at runtime).

Note that the iterate function would not be appropriate for what I am doing, since I do not care about any intermediate results.

like image 234
kes Avatar asked Oct 12 '10 01:10

kes


People also ask

How do you write a function with itself?

Composing a Function with Itself To compose a function with itself, we simply input a function into itself using the definition of composition of functions. In other words, to compose a function, f(x) , with itself, we compute f(f(x)) f ( f ( x ) ) or (f∘f)(x) ( f ∘ f ) ( x ) .


2 Answers

The iterate solution is fine, or you might like this one: the composition of n copies of f is foldr (.) id (replicate n f).

like image 157
Reid Barton Avatar answered Sep 25 '22 14:09

Reid Barton


\xs n -> iterate func xs !! n 

(xs is the initial value, n is the number of times to apply func)

I don't know why, but I feel like iterate is something people aren't consistently exposed to when learning Haskell.

If you don't like !! then you could use zip and lookup as an alternative. (some people/groups/tools don't like functions that call "error" in certain cases, I'm not claiming lookup is any better in these cases)

lookup n . zip [0..] . iterate func 

EDIT: Ok, so I deleted then undeleted because I agree with the other answerer - you shouldn't discount use of iterate just because it gives you more than you need.

like image 38
Thomas M. DuBuisson Avatar answered Sep 23 '22 14:09

Thomas M. DuBuisson