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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With