beginner first-steps

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.

Part of: Install and setup

In Clean Language, functions live in a functions: block:

start:
	print(greet("Alice"))
	print(greet("Bob"))
	print(greet("everyone"))

functions:
	string greet(string name)
		return "Hello, {name}! Welcome to Clean Language."
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:

start:
	print(double(5).toString())
	print(addTen(7).toString())
	print(double(addTen(3)).toString())

functions:
	integer double(integer n)
		return n * 2

	integer addTen(integer n)
		return n + 10
10
17
26

You can pass a function's result directly into another function. addTen(3) gives 13, then double(13) gives 26. Functions compose naturally.

  • 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")
📚 → Book 1, Chapters 15–17 : Classes →
Copied!