From 17803d8ab9de1af7029b7677ff682be407a10fac Mon Sep 17 00:00:00 2001 From: Garrit Franke Date: Sun, 7 Feb 2021 14:50:42 +0100 Subject: [PATCH] docs: document functions --- TODO | 1 + docs/concepts/functions.md | 34 ++++++++++++++++++++++++++++++---- examples/playground.sb | 6 +++--- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/TODO b/TODO index 549a8bc..9084d76 100644 --- a/TODO +++ b/TODO @@ -6,6 +6,7 @@ - stdlib moves line of file, which makes error reporting impossible # Features +- Expect return statement if specified in function - Type inference - Multi-file support - Argument overloading diff --git a/docs/concepts/functions.md b/docs/concepts/functions.md index b433359..8cb84b1 100644 --- a/docs/concepts/functions.md +++ b/docs/concepts/functions.md @@ -33,10 +33,36 @@ fn another_function(x: int) { } ``` -## Functions contain statements +## Return types -TODO +Functions can optionally return a value. To specify the return type, it is added to the function signature, similar to how variables and parameters do. Here's a simple example of a function that returns an integer: -## Return types +``` +fn add_one(x: int): int {} +``` + +Note that this function won't compile, since it doesn't actually return anything. Let's fix that by adding a `return` statement with an expression: + +``` +fn add_one(x: int): int { + return x + 1 +} +``` + +Now, if you call the function with `1` as its argument and read its value, you will see the computed result: -TODO +``` +fn main() { + let result = add_one(1) + println(result) +} + +fn add_one(x: int): int { + return x + 1 +} +``` + +``` +$ sabre run main.sb +2 +``` diff --git a/examples/playground.sb b/examples/playground.sb index cfa9395..7d6dc27 100644 --- a/examples/playground.sb +++ b/examples/playground.sb @@ -1,8 +1,8 @@ fn main() { - let x = two() + let x = add_one(2) println(x) } -fn two(): int { - return 2 +fn add_one(x: int): int { + return x + 1 } \ No newline at end of file