Functions
Define a function with to, followed by its name, its parameters, and an indented body.
Otter
to greet person
say "Hello," person
.
greet "Ada"
greet "Linus"
Output
Hello, Ada
Hello, Linus
Return values
Otter
to calculateTax subtotal and rate
subtotal times rate make tax
return tax
.
# Option A: using make
calculateTax 100 and 0.08 make taxAmount
say "Tax on $100:" taxAmount
# Option B: using is
taxAmount2 is calculateTax 200 and 0.05
say "Tax on $200:" taxAmount2
Output
Tax on $100: 8
Tax on $200: 10
Scope
Every call gets its own scope. Parameters never overwrite variables outside the function:
Otter
name is "Outside"
to greet name
say "Hello" name
.
greet "Jeff"
say name
Output
Hello Jeff
Outside
Arguments are single values
Each argument is one value: a number, a piece of text, a variable or a property. A call takes exactly as many values as the function has parameters, so factorial n minus 1 means (factorial n) minus 1, not the factorial of n minus 1, and that call would never end. Put a calculation in a variable first, then pass the variable. A function must also be defined above the line that calls it.
Otter
to factorial n
if n is at most 1
return 1
.
m is n minus 1
rest is factorial m
return n times rest
.
say factorial 5
Output
120
stop ends a function early. Larger programs can be split across files with use "other.ot".
Next: objects and properties