Combining Functions
Another method to create function values could be defined as combining existing function values.
It may be seen as irrelevant but it is maybe the most important, because it reflects what Functional Programming is about.
An example of combining existing functions could be this.
In our first example we had something like:
put map [ add [2] ] [ [10,15,20,30] ]
Now what if we omit the second parameter and assign the result to a new variable?
List_Add2 = map [ add [2] ]
We obtained another function from map and add. This function will add 2 to all elements of a list that will be supplied as parameter.
For example
put List_Add2 [ [10,15,20,30] ]
-- [12, 17, 22, 32]
put List_Add2 [ [1,-10,2] ]
-- [3, -8, 4]
Example: IfThenElse function is defined in LingoF module and modulo in the Lingo module, because it represent Lingo’s mod operator.
I want to combine them to obtain the IsOdd function that will behave this way:
put IsOdd[2]
-- "no"
put IsOdd[3]
-- "yes"
The problem with modulo is that I need to leave the first parameter free and fix the second with 2.
I can do something like Currying, using the skip function. Skip is also implemented with the _ shortcut. It allows me to skip one parameter, so I can write:
$ = LingoF().open(#lingo)
put modulo._[2] [35]
-- 1
This is a shortcut for:
$ = LingoF().open(#lingo)
put $.skip[ $.modulo ] [2][35]
Skip is implemented using a method in the function value object, the .skip() method. So we can consider Skip as a primitive.
Now we need to respond “yes” or “no” instead of 1 or 0. In LingoF module is defined the compose function.
on public_Compose_3
on Compose me, f,g,x
return f[g[x]]
end
It’s shortcut is @. Note that, in contrast to skip, compose is implemented without special primitives.
Composing IfThenElse._["yes"]["no"] with our previous function should be enough.
IsOdd = $.IfThenElse._["yes"]["no"] .@ [ $.modulo._[2] ]
We will go back to this problem with lambda expressions.