Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - compose function n times

Tags:

scala

scalaz

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?

like image 794
Dominic Bou-Samra Avatar asked Jan 25 '14 04:01

Dominic Bou-Samra


Video Answer


2 Answers

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
like image 188
Marth Avatar answered Oct 16 '22 21:10

Marth


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
like image 5
DaoWen Avatar answered Oct 16 '22 20:10

DaoWen