Scala - compose function n times

只愿长相守 提交于 2019-12-04 18:07:01

问题


I have a function that looks like this:

def emulate: (Cpu => Cpu) => (Cpu => Cpu) = render => {
  handleOpcode   andThen
  handleTimers   andThen
  handleInput    andThen
  debug          andThen
  render
}

I want to call the handleOpcode function n number of times (say 10 times). In Haskell I might write a function like so:

ntimes n f = foldr (.) id (replicate n f)

But in Scala, I'm not sure how I might write it. I tried:

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

but the types are all wrong.

Is there a simple way to achieve this? Ideally without having to create my own function. Something in Scalaz perhaps?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/21346479/scala-compose-function-n-times

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