11

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?

Dominic Bou-Samra
  • 14,799
  • 26
  • 100
  • 156
  • 3
    Well, `f` is not a function there, it's just a non-strict `Any`, so it's no surprise the types are all wrong. Why don't you start writing the types just as you did in Haskell? – Daniel C. Sobral Jan 25 '14 at 05:28

2 Answers2

14

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
Marth
  • 23,920
  • 3
  • 60
  • 72
5

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
DaoWen
  • 32,589
  • 6
  • 74
  • 101