The Zeno Book Zeno 0.1 zeno-lang.org

8 Functions

A function is a block of code with a name, which the rest of the program can run by calling it. Functions are how a program is cut into pieces small enough to understand one at a time.

8.1 Declaring and calling

function area(width: float, height: float) -> float {
    return width * height
}

print(area(2.0, 3.0))
print(area(1.5, 4.0))
6.0
6.0

The first line is the function’s heading: the word function, a name, the parameters in brackets with their types, and after -> the type of what it gives back. Calling it gives each parameter a value, the arguments, and return hands a value back to the caller and ends the call.

function is a whole word that someone who has never seen the language can read aloud. fn and def have to be learnt, and editor completion makes the extra letters free. (Decision 1.4.)

A function that gives nothing back leaves out the -> part. Its call is then worth none:

function announce(what: str) {
    print("now:", what)
}

let result = announce("lunch")
print(result)
now: lunch
none

8.2 Types are optional here too

The types in a heading can be left out:

function add(a, b) {
    return a + b
}
print(add(1, 2))
3

Zeno works out what it can. Here every call passes two ints, so a and b are ints, and the function gives an int. If a call disagrees with how the function uses its parameters, the mistake is reported inside the function, with a note that names the line the type was worked out from:

function shout(text) {
    return text.upper()
}
print(shout(5))
error: int has no field or method `upper`
 --> main.zeno:2:12
  |
2 |     return text.upper()
  |            ^
  = note: `text` was worked out to be int from line 4. Give `text` a type to have each call checked against it instead

1 error found. Nothing was run.

When the types are written, every call is checked against them, and a wrong call is reported at the call:

function shout(text: str) -> str {
    return text.upper()
}
print(shout(5))
error: `text` of `shout` should be str, but this is int
 --> main.zeno:4:13
  |
4 | print(shout(5))
  |             ^

1 error found. Nothing was run.

That is the reason to write types on anything that other people call. Types, Written and Worked Out says exactly what Zeno works out, and when it cannot.

8.3 Returning on every path

A function that promises to return a value must return one on every way through it. Zeno finds the way that falls off the end:

function sign(n: int) -> int {
    if n > 0 {
        return 1
    } else if n < 0 {
        return -1
    }
}
error: `sign` can reach its end without returning the int it promises
 --> main.zeno:1:1
  |
1 | function sign(n: int) -> int {
  | ^

1 error found. Nothing was run.

In C, falling off the end of a function that promised a value returns whatever was lying in a register. In Python it returns None, which then fails somewhere else. Here it is an error at the function. (Decision 3.13.)

8.4 Default values

A parameter can have a default, used when the call leaves it out:

function greet(who: str, excited: bool = false) -> str {
    if excited {
        return f"Hello, {who}!"
    }
    return f"Hello, {who}."
}

print(greet("Ada"))
print(greet("Ada", true))
Hello, Ada.
Hello, Ada!

A default is worked out afresh on every call, so a default list is a new empty list each time:

function with_one(items: list[int] = []) -> list[int] {
    items.append(1)
    return items
}
print(with_one(), with_one())
[1] [1]

In Python, def add(item, to=[]) makes the list once, and every call shares it, so the second call finds the first call’s item. It is one of the most reported surprises in that language. (Decision 3.5.)

8.5 Named arguments

Any argument can be given by the name of its parameter, which makes a call readable without looking the function up:

function set_timer(millis: int, repeat: bool, start_now: bool) {
    print(millis, repeat, start_now)
}

set_timer(500, true, false)
set_timer(millis=500, repeat=true, start_now=false)
set_timer(500, repeat=true, start_now=false)
500 true false
500 true false
500 true false

Plain arguments come first and named ones after them. A name that is not a parameter, or a parameter given twice, is a mistake:

function move(x: int, y: int) {
    print(x, y)
}
move(1, z=2)
error: `move` needs a value for `y`
 --> main.zeno:4:1
  |
4 | move(1, z=2)
  | ^

error: `move` has no argument named `z`
 --> main.zeno:4:11
  |
4 | move(1, z=2)
  |           ^

2 errors found. Nothing was run.

8.6 Parameters do not change

A parameter holds what the caller passed, all the way through the function. It cannot be given another value; if the function needs a changing value, it makes a var of its own:

function count_down(start: int) {
    while start > 0 {
        start -= 1
    }
}
error: `start` cannot be changed. Declare it with `var` to allow that
 --> main.zeno:3:9
  |
3 |         start -= 1
  |         ^

1 error found. Nothing was run.
function count_down(start: int) {
    var n = start
    while n > 0 {
        print(n)
        n -= 1
    }
}
count_down(3)
3
2
1

A list or an object passed as an argument is the caller’s own, not a copy, so a function can change what is inside it, and the caller sees the change. Lists returns to this.

8.7 Calling a function above where it is written

A function can be used anywhere in its file, above or below the place it is declared. That lets a file read from the top, with the main logic first and the helpers below:

print(fahrenheit(100.0))

function fahrenheit(celsius: float) -> float {
    return celsius * 1.8 + 32.0
}
212.0

The same goes for classes and enums. Variables are different: a let or var exists only from its line on.

8.8 Functions that call themselves

A function may call itself. This is called recursion, and it suits problems that contain smaller copies of themselves:

function factorial(n: int) -> int {
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}

function fib(n: int) -> int {
    if n < 2 {
        return n
    }
    return fib(n - 1) + fib(n - 2)
}

print(factorial(20), fib(20))
2432902008176640000 6765

8.9 Functions inside functions

A function can be declared inside another. It is then a name of that block, like a variable, and can use the variables that were declared above it in the blocks around it:

function report(readings: list[float]) {
    let limit = 25.0

    function flag(r: float) -> str {
        if r > limit {
            return "high"
        }
        return "ok"
    }

    for r in readings {
        print(r, flag(r))
    }
}

report([21.0, 27.5])
21.0 ok
27.5 high

What such a function can see is fixed by where it is written: the variables above it, never one declared further down. A function used before a variable it needs has been declared is refused, with the reason:

function outer() -> int {
    let result = inner()
    let base = 5
    function inner() -> int {
        return base * 2
    }
    return result
}
print(outer())
error: `base` is declared further down than the first use of `inner`, which needs it. Use `inner` below the line that declares `base`
 --> main.zeno:5:16
  |
5 |         return base * 2
  |                ^

1 error found. Nothing was run.

Functions are also values, which can be stored, passed and returned, and a function written inside another can go on using its variables after the outer one has returned. That is the subject of Functions as Values.

A function has a heading, function name(parameters) -> type, and a body. Types can be written or left out. A function that promises a value must return one on every path, and one that promises nothing returns none. Defaults are worked out on every call, arguments can be named, parameters never change, and functions can be called from above where they are written, call themselves, and live inside other functions.

  1. Write function clamp(x: float, low: float, high: float) -> float and call it with named arguments in a different order from the heading.

  2. Remove the types from clamp and call it with ints. Then add a call with a str. Where is the mistake reported?

  3. Write power(base: int, exponent: int) -> int that calls itself, using base ** exponent == base * base ** (exponent - 1).

  4. Write a function with a while true loop and a return inside it. Does Zeno ask for a return after the loop?