4. Functions
This chapter shows how to define and call functions: typed parameters, return types, recursion, and the method-call shorthand x.f(). It also introduces the first of Tern's safety rules, that a function can't change its parameters, and shows how to return more than one result and report failure without exceptions.
Defining a function
A function starts with fn, lists its parameters with their types, and puts the return type after the ):
fn area(width: float, height: float) float:
return width * height
fn describe(name: str, sides: int) str:
return f"a {name} has {sides} sides"
fn announce(msg: str):
print("** " + msg + " **")
fn main():
print(area(3.0, 4.5))
print(describe("hexagon", 6))
announce("done")13.5
a hexagon has 6 sides
** done **- Every parameter needs a type. Types are how the compiler catches mistakes at the call site, and they document the function for the next reader.
- The return type follows the
)with no arrow, as in Go. (-> floatis also accepted if you are used to Python annotations or Rust.) - A function with no return type, like
announce, returns nothing. You can usereturnwith no value to leave it early. - Functions can be called before they are defined in the file, so you can order them however reads best. Most programs put
mainlast or first.
There are no default parameter values, keyword arguments, variable numbers of arguments, or overloading (two functions with the same name). Each function has one signature, and every call passes every argument in order. This keeps calls easy to read: what you see at the call site is everything the function gets.
Every path must return
If a function has a return type, every way through it must end in return. The compiler checks this:
fn sign(n: int) str:
if n > 0:
return "positive"
elif n < 0:
return "negative"
fn main():
print(sign(3))1: error: function `sign` must end with a `return`What should sign(0) return? The compiler can't guess, so it asks you to decide. Adding an else branch (or a final return "zero") fixes it.
Recursion
Functions may call themselves:
fn factorial(n: int) int:
if n <= 1:
return 1
return n * factorial(n - 1)
fn gcd(a: int, b: int) int:
if b == 0:
return a
return gcd(b, a % b)
fn main():
print(factorial(10), gcd(84, 36))3628800 12Method-call syntax
There are no classes, but any function can be called as if it were a method: x.f(a, b) is exactly the same call as f(x, a, b). The value before the dot becomes the first argument:
fn shout(s: str) str:
return s.upper() + "!"
fn clamp(n: int, lo: int, hi: int) int:
if n < lo:
return lo
if n > hi:
return hi
return n
fn main():
print(shout("hello"), "hello".shout())
print(clamp(150, 0, 100), 150.clamp(0, 100), (-5).clamp(0, 100))HELLO! HELLO!
100 100 0This is how built-in functions like upper work too, and it is how you will write "methods" for your own structs in the next chapter.
Parameters are read-only
Here is the first rule that is different from most languages. Inside a function, you can't change a parameter:
fn countdown(n: int):
while n > 0:
print(n)
n -= 1
fn main():
countdown(3)4: error: can't modify parameter `n`: parameters are read-only unless declared `mut`
4: hint: to change only a local copy, copy it first (`n2 = n`) and change `n2`; to change the caller's value, declare `n: mut T` and call with `f(&x)` or `x.f()`Why? In Tern, a function receives its arguments as values, never as references. If a function could quietly change its parameters, a reader could not tell whether countdown(x) changes x or not. So parameters are read-only, and when a function is allowed to change the caller's variable, both the function and the call say so (mut and &, chapter 9). For now, the fix is the first half of the hint: copy the parameter into a local variable and change that.
fn countdown(n: int):
left = n
while left > 0:
print(left)
left -= 1
print("go")
fn main():
countdown(3)3
2
1
goThe copy costs nothing for an int, and even for a large array it is cheap: Tern copies lazily, only when one side is actually written.
Returning more than one value
To return several values, return a tuple: write the types in parentheses after the ), return the values separated by commas, and unpack them at the call:
fn min_max(xs: [int]) (int, int):
lo = xs[0]
hi = xs[0]
for x in xs:
if x < lo:
lo = x
if x > hi:
hi = x
return lo, hi
fn main():
temps = [18, 23, 15, 27, 21]
lo, hi = min_max(temps)
print("low", lo, "high", hi)low 15 high 27For more than two or three values, a struct (the next chapter) with named fields reads better. A function can also change variables the caller passes in with &, when their parameters are declared mut:
fn widen(lo: mut int, hi: mut int, by: int):
lo -= by
hi += by
fn main():
lo = 15
hi = 27
widen(&lo, &hi, 5)
print(lo, hi)10 32lo: mut int means "this function may change the caller's variable", and the caller marks each such argument with &. You can see at the call site exactly which variables might change. Chapter 9 explains mut fully.
Reporting failure
There are no exceptions. A function that can fail returns a Result: either Ok(value) or Err(why). The caller checks which it got, here with is, which also names the value inside:
fn parse_percent(text: str) Result[int, str]:
n = text.to_int(-1)
if n < 0 or n > 100:
return Err(f"{text} is not a percentage")
return Ok(n)
fn main():
for input in ["42", "150", "abc"]:
r = parse_percent(input)
if r is Ok(value):
print(input, "->", value)
elif r is Err(why):
print(why)42 -> 42
150 is not a percentage
abc is not a percentageA value that may simply be missing is an Option: Some(value) or None. Chapter 8 has more on both, including ?, which passes a failure up to the caller in one character.
text.to_int(-1) parses a string as an int, giving -1 if it isn't a number. The strings chapter covers it and similar functions.
Sharing a name with a builtin
Built-in functions such as get, find, len, and min need no import. Your own functions can have the same names. A call goes to yours when its first argument fits your first parameter, and to the builtin otherwise:
struct Inventory:
counts: {str: int}
fn get(inv: Inventory, item: str) int:
return inv.counts.get(item, 0) # the builtin: counts is a map
fn main():
inv = Inventory({"apple": 3})
print(inv.get("apple"), inv.get("pear"), get(inv, "apple"))3 0 3The full list of builtins is in §20 of the reference.
Try it
Write fn is_prime(n: int) bool that checks divisors from 2 while d * d <= n, and use it to print the prime numbers below 30 on one line. Since print always ends the line, build the line as a string first and print it once. Then write fn count_primes(limit: int) int that calls is_prime as a method: n.is_prime().
Solution
fn is_prime(n: int) bool:
if n < 2:
return false
d = 2
while d * d <= n:
if n % d == 0:
return false
d += 1
return true
fn count_primes(limit: int) int:
count = 0
for n in 0..limit:
if n.is_prime():
count += 1
return count
fn main():
line = ""
for n in 0..30:
if is_prime(n):
line += str(n) + " "
print(line.trim())
print(count_primes(1000), "primes below 1000")2 3 5 7 11 13 17 19 23 29
168 primes below 1000Next: 5. Structs. Reference: §6 Functions.