function composition of anytype A

Viewed 78
def iter[A](f: A => A, n: Int): A => A = {
  if (n == 1) { 
    f
  } else {
    f(iter(f,n-1))
  }
}

I want to make a function iter that makes function composition of f, for example:

iter(f,1) = f
iter(f,2) = f(f)

But I can't find a way how to pass type A into function f recursively, how can I solve this problem?

1 Answers

Note that in your code f(iter(f,n-1)) where f accept an instance of A but iter(f, n-1) with type A => A.

Here is a solution:

scala> def iter[A](f: A => A, n: Int): A => A =
     |   if (n == 0) identity else f.compose(iter(f, n-1))
     |
def iter[A](f: A => A, n: Int): A => A

scala> iter[Int](x => x + 1, 10)(0)
val res0: Int = 10

Or without compose:

scala> def iter[A](f: A => A, n: Int): A => A =
     |   if (n == 0) identity else x => iter(f, n-1)(f(x))

Or even simple:

scala> def iter[A](f: A => A, n: Int): A => A = Function.chain(Seq.fill(n)(f))
Related