Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 408
ccheneson Avatar asked Jul 22 '14 09:07

ccheneson


People also ask

What is meant by function composition?

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.

Is composition of function commutative?

Composition of functions is different from multiplication of functions, and has quite different properties; in particular, composition of functions is not commutative.

How do you express a function as a composition?

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)) .

What is the rule in composition of functions?

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.


1 Answers

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
like image 108
Marth Avatar answered Sep 28 '22 16:09

Marth