HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Cleaner way for coding a repetitive application of a function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
applicationwayfunctionrepetitiveforcleanercoding

Problem

I have this function definition which takes an r and applies the function f n times:

r => (1 to n).foldLeft(r)((rx, _) => f(rx))


So for n=3 this is equivalent to f(f(f(r)))

I don't like this solution, because it defines a Range from 1 to n which really isn't get used at all, which becomes obvious in the unused parameter _ in the fold left. This in turn forces me to give a separate name to rx which feels wrong to me.

Any idea how I can streamLine this code?

Solution

What's wrong with straight recursion?

def ntimes[A](n:Int, f:A=>A, a:A):A = if (n==0) a else ntimes(n-1, f, f(a))


Another clean option is

Iterator.iterate(a)(f).drop(n).next

Code Snippets

def ntimes[A](n:Int, f:A=>A, a:A):A = if (n==0) a else ntimes(n-1, f, f(a))
Iterator.iterate(a)(f).drop(n).next

Context

StackExchange Code Review Q#18990, answer score: 7

Revisions (0)

No revisions yet.