Functions as Data Types
In Type-C, functions are first-class citizens, allowing them to be assigned to variables, passed as arguments, or returned from other functions. The language supports the definition of custom types for functions, streamlining their use in various contexts. Currently, the variable name has to be present within a function type despite not really being used.
Example
The snippet defines a custom function type, FunctionType, designed for functions that accept a ServerResponse and return void. This custom type enhances code readability by making explicit the expected function signature. The example also demonstrates a higher-order function, apply, which takes a function f and an array arr, and returns a new array obtained by applying f to each element of arr. This showcases how function types can simplify the manipulation and use of functions as data.
Argument Mutability
When it comes to type compatibility between function types, not only arguments types must be compatible, but also their mutability must be compatible. For example, a function that takes a mutable argument cannot be assigned to a variable of type function that takes an immutable argument. However, the opposite is possible, a function that takes an immutable argument can be assigned to a variable of type function that takes a mutable argument. This is to ensure that the expected mutability of the argument is preserved.
Function Overloading
It is possible to overload functions, with some limitations.
- Functions must have different argument types. Return types does not count towards the signature
- Overloaded functions must be within the same scope