Scala - compose function n times

核能气质少年 提交于 2019-12-03 12:32:20

You could use the Function.chain method :

scala> val add1 = (x:Int) => x+1
add1: Int => Int = <function1>

scala> val add5 = Function.chain(List.fill(5)(add1))
add5: Int => Int = <function1>

scala> add5(5)
res1: Int = 10

I'm not sure if there's something more elegant provided by Scalaz, but your solution should work fine if you massage the types a bit:

def nTimes[T](n: Int, f: T=>T) = {
  val l = List.fill(n)(f)
  l.foldRight(identity: T=>T){ (x, y) => y.andThen(x) }
}

// example
def inc(i: Int) = i+1

nTimes(5, inc)(0)
// => 5
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!