Functions

Creating Functions

To create functions, the function keyword can be used. This may be familiar to some from other languages that have similar keywords.

Visibility

Every function requires a predetermined visibility attribute.

KeywordExplanation
publicA public function is publicly available in the module.
privateA private function is only available in the module it is defined in.

Every source file serves as a different module.

Function statement:

<visibility> function <name>(<arguments>): <return type> {
    <body>
}

Function definition example:

pub function name(arg1: int, arg2: float) {
    // Function body
}

pub function name_2(arg1: int, arg2: float): int {
    // Function body

    return 0;
}

Generics as arguments

Generics can also be used in function arguments to help with the object-orientedness of the language.

pub function foo |<generic's name>: <trait1> + <trait2>, <...>|: int {
    foo.trait1_fn()
}

Consult the traits page for further information.

Importing Functions

We can import functions from other source files or from libc.

  • To import functions from pre-compiler libraries, we can use the external keyword.
  • When importing functions from dependencies or from other fog source files we can import the item via defining the the module path.
  • We can import source files by manually defining their paths on the host system.

Here is how to import both types of functions:

// -- other.f --
pub function return_2(): int {
    return 2;
} 

// main.f
import "other.f";

// Import with a fully defined path
import "foo/bar/faz/test.f";

// Importing from a precompiled library (libc in this case)
external printf(msg: string, ...): void;

// Importing from a source file
import other::return_2;

// Importing from a dependency
import foo::bar::baz::hello;

pub function main(): int {
    int num = return_2();

    // Greet the user
    hello();

    printf("Returned number: %i", num);

    return 0;
}

Note that we can also use variable arguments when constructing symbols for other functions. VarArgs cannot be used in a Fog function.