ccheneson
ccheneson

Reputation: 49410

Function composition dynamically

Let' s say I have a function move.

Now, depending on some inputs (let' s say the input says "Move by 3"), I have to move 3 times.

I would do this like :

move compose move compose move

Is it possible to do function composition dynamically? So that I can build my new function depending on the number of times I have to move.

Thank you

Upvotes: 4

Views: 383

Answers (2)

Marth
Marth

Reputation: 24802

You could use the Function.chain method :

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

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

scala> move5(5)
res1: Int = 10

Upvotes: 10

gzm0
gzm0

Reputation: 14842

Just use a fold:

def move(x: Int): Int = x + 1

def moveBy(n: Int) = 
  (1 to n).foldLeft[Int => Int](identity _) { (f, _) => f compose move }

moveBy(5)(0) // > 5

Upvotes: 4

Related Questions