-
Couldn't load subscription status.
- Fork 0
Functions
Algo is at heart a functional language, so functions are extremely flexible, and can be passed around like any other variable, and called as a delegate that way. To define a function, you can do the following:
let f(x) = {
print "You passed in '" + x + "'!";
}
This defines a function with one parameter, x, which can then be mutated and used within the function. In this case, it prints whatever was passed in back to the user! To add more parameters, you simply add a comma, and then another name. They can't be duplicate, so don't use x twice.
let f(x, y) = {
...
}
What if you want to return a value from a function? Well, you use the return keyword inside a function. This can return nothing, and simply exit the function (return; with no value) or return a given value (return [expr];). Here are some examples of returning values for illustration purposes:
//define a function that returns something
let f(x) = {
return x + 2;
}
//get a number to put into the function
let number = 3;
//call the function and get something back
let numberPlusTwo = f(number);
print "The number 3 plus two is " + numberPlusTwo + ".";
//define a function that prints things
let f(x) = {
if (x != "hello world")
{
return;
}
print "Hello to you too!";
}
f("bar"); //this doesn't print anything
f("hello world") //this prints "Hello to you too!"
To pass a function as a delegate, for use as a callback function or other, you can simply pass functions like any other variable. Here's an example of calling a callback function that's passed in with some parameters.
//an example callback function which prints things
let callback(somevar) = {
print "the provided number plus 2 is " + somevar;
}
let f(x, cb) = {
x += 2;
//call the callback with x as a parameter
cb(x);
}
//pass in the callback function as a parameter here
f(4, callback); //prints "the provided number plus 2 is 6"
Algo (c) Larry Tang, 2019.
Commercial use of Algo must include the LICENSE file in the same directory as the executable.
Standard Library Documentation: