-
Notifications
You must be signed in to change notification settings - Fork 2
Functions and anonymous functions
After having learned about variables and basic types, we want to create more complex programs that especially interact with user-defined variables. This is where functions come into play. Functions are a way to define a block of code that can be executed multiple times with different arguments. In Plume, functions are first-class citizens, meaning that they can be passed as arguments to other functions, returned from other functions, and assigned to variables.
Unlike variables, functions need a specific keyword to be defined. In Plume, this keyword is fn.
// Declare a function named `add` that takes two arguments `a` and `b` and returns their sum
fn add(a: int, b: int): int => a + b// Declare a function that add twice the value of `a` to the value of `b`
fn add_twice(a: int, b: int): int {
c = add(a, a)
return add(c, b)
}In the previous example, return has been used in one case and not in the other. This is because the return statement depends on the context of the function. If the function is a block of code, you need to use the return statement to return a value. If the function is an inline expression, you may omit it.
Anonymous functions are functions that are declared without a name. They are useful when you need to pass a function as an argument to another function or when you need to return a function from another function.
// Declare a function that apply a function to a value
fn apply<A, B>(f: (A) -> B, value: A): B => f(value)
// Use the `apply` function to apply an anonymous function to a value
result = apply(fn x => x + 1, 42) // This will return `43`In the previous example, the apply function has been declared with generic types. This is a way to make the function more flexible and to accept any type of value. The A and B types are placeholders that will be replaced by the actual types when the function is called.
Generics permit to writing of more generalized code and to avoid code duplication.
As said before, functions are first-class citizens in Plume. This means that they may be better typed than a simple int or str. In Plume, you can define a function type by writing fn(A, B, C, ...): R where A, B, C, ... are the types of the arguments and R is the type of the return value.
So add's type would be fn(int, int): int, and apply's type would be fn(fn(A:) B, A): B.