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
In Maths, the composition of a function is an operation where two functions say f and g generate a new function say h in such a way that h(x) = g(f(x)). It means here function g is applied to the function of x. So, basically, a function is applied to the result of another function.
Composition of functions is different from multiplication of functions, and has quite different properties; in particular, composition of functions is not commutative.
The composition of two functions g and f is the new function we get by performing f first, and then performing g. For example, if we let f be the function given by f(x) = x2 and let g be the function given by g(x) = x + 3, then the composition of g with f is called gf and is worked out as gf(x) = g(f(x)) .
The composite function rule shows us a quicker way. If f(x) = h(g(x)) then f (x) = h (g(x)) × g (x). In words: differentiate the 'outside' function, and then multiply by the derivative of the 'inside' function.
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
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