Lesson 5 — Functions
You are here
- Your first program ✓
- Values and variables ✓
- Making decisions ✓
- Repeating things ✓
- Functions ←
- Lists and hashes
- Strings
- Organizing programs
- Classes
What are we learning?
A function is a named group of instructions you can run whenever you need them.
Smallest useful example
echo
fn greet() {
say("Hello!");
}
greet();Output
text
Hello!Line by line
fn greet()— define a function namedgreetwith no inputs.{ ... }— the instructions that belong togreet.greet();— run those instructions.
Defining a function does not run it. Calling greet(); does.
Inputs (parameters)
A parameter is a name for a value you pass in when you call the function.
echo
fn greet(name: str) {
say("Hello,", name);
}
greet("Echo");Output
text
Hello, Echoname: str— this function expects text.greet("Echo");— pass the textEchoin.
Answers back (return)
Some functions give a value back. You mark the kind of answer with ->, and use return:
echo
fn add(a: int, b: int) -> int {
return a + b;
}
say(add(2, 3));Output
text
5-> int— this function’s answer is a whole number.return a + b;— send that answer back to the caller.say(add(2, 3));— runadd, then print the answer.
Try it
Write a function shout that takes a str and prints it. Call it once.
Predict it
echo
fn twice(n: int) -> int {
return n * 2;
}
say(twice(4));Show answer
text
8Fix it — return needs a return type
This fails:
echo
fn f() {
return;
}If you use return, write a return type. For “no value,” use void:
echo
fn f() -> void {
return;
}Deeper (later)
Reading and changing names from outside a function (use / use mut), lambdas, and advanced shapes are in Functions (full) and Scope, use, and watch. You do not need them yet.
