Skip to content

Functions

Utku Melemetci edited this page May 17, 2024 · 1 revision

You can use functions to break up your program logic into more manageable pieces. For example,

func say_hi() {
    std::print_string("hi")
}

func main() {
    say_hi() 
}

Note that say_hi must come before main.

Any number of function parameters (as long as your computer has enough stack space!) is also supported:

func say_hi_and_print(n: Int) {
    std::print_string("Hi! ")
    std::print_int(n)
    std::print_endline()
}

func main() {
    say_hi_and_print(10)
}

Functions can return values:

func returns() -> Int {
    return 1
}

func main() {
    let result = returns()
    std::print_int(result)
    std::print_endline()
}

And, finally, you can even use recursion! But this isn't OCaml, so there is no tail-call optimization. Be careful.

func fib(n: Int) -> Int {
    if n == 0 {
        return 0
    } 
    if n == 1 {
        return 1
    }
    return fib(n - 1) + fib(n - 2)
}

func main() {
    let result = fib(10)
    std::print_int(result)
    std::print_endline()
}
Clone this wiki locally