Writing Your Own Functions
As your programs grow, you'll find yourself writing the same code in different places. Functions are the solution — write something once, use it anywhere.
In Clean Language, functions live in a functions: block:
functions:
string greet(string name)
return "Hello, {name}! Welcome to Clean Language."
start:
print(greet("Alice"))
print(greet("Bob"))
print(greet("everyone"))Hello, Alice! Welcome to Clean Language.
Hello, Bob! Welcome to Clean Language.
Hello, everyone! Welcome to Clean Language.The function is named greet, takes one string input called name, and returns a string. Write the return type first, then the function name, then parameters in parentheses.
Functions can do calculations too:
functions:
integer double(integer n)
return n * 2
integer addTen(integer n)
return n + 10
start:
print(double(5).toString())
print(addTen(7).toString())
print(double(addTen(3)).toString())10
17
26You can pass a function's result directly into another function. addTen(3) gives 13, then double(13) gives 26. Functions compose naturally.
Quick recap
- Declare functions in a functions: block, outside of start:
- Write the return type first: integer, string, boolean, void
- Parameters go inside parentheses: (string name, integer age)
- Use return to send a value back
- Call a function by name: greet("Alice")