Composing a function n times with itself
Today I faced this question from a tweet by Sash Zats: how does one call a function n times, using as a parameter for each call the result of the previous call?
Sure, assuming we want to call a function 5 times, one might just do this:
But is that what we really want to write?
Standard Library to the Rescue
I did some research, then found a response from Chris Eidhof, which mentioned a type called UnfoldSequence
.
Turns out, the Standard Library has a function called sequence(first:next:)
that does just that. From the documentation:
Returns a sequence formed from
first
and repeated lazy applications ofnext
.
For completeness, here’s the entire function signature:
But we need something more right? We need to control the number of times the function needs to be called. We don’t want to clutter the call site with a bunch of calls to next()
.
So I went one step further and wrote this little function that does just what we need:
Please note that we call next()
n+1 times because otherwise the first call would result in the initial input being the output.
Wrapping up
We’ve seen how very little bit of work and some help from the Standard Library can make our life easier. Let’s see the final result!
You can find the complete code in this gist.
Hope you find it helpful! :)