From b6a2e83b6a1464cd4dad074c20c460b075dbbe61 Mon Sep 17 00:00:00 2001 From: henesy Date: Mon, 4 Mar 2019 21:55:44 -0600 Subject: [PATCH] add Functions example --- Functions/README.md | 36 ++++++++++++++++++++++++++++++++++++ Functions/func.b | 38 ++++++++++++++++++++++++++++++++++++++ README.md | 1 + 3 files changed, 75 insertions(+) create mode 100644 Functions/README.md create mode 100644 Functions/func.b diff --git a/Functions/README.md b/Functions/README.md new file mode 100644 index 0000000..42754b9 --- /dev/null +++ b/Functions/README.md @@ -0,0 +1,36 @@ +# Functions + +Functions in Limbo are similar to functions in Go moreso than functions in C. + +## Source + +### func.b:13,17 + +This section shows a function prototype as well as the succeeding function definition. Prototypes in Limbo function similar to prototypes in C. + +The function `plus()` takes two integers as arguments and returns their sum. + +### func.b:19,21 + +The function `swp()` takes two integer arguments and returns two integers within a tuple. + +Note that the type statement `: int` is only provided once, with the list of variables to the left of the type statement being declared to be integers. + +### func.b:36,38 + +The function `plusplus()` takes three integer arguments and returns their sum, calling the function `plus()` in the process to sum the first two arguments. + +The return value of `plus()` is a single variable, so it can be added to `c` without any extra syntactical structures than using the return value as an unnamed variable. + +## Demo + + ; limbo func.b + ; func + 3 + 5 = 8 + 7 + 3 + 4 = 14 + swap 6,7: 7,6 + ; + +## Exercises + +- Try returning more than two values, can tuples store more than two ordered objects? diff --git a/Functions/func.b b/Functions/func.b new file mode 100644 index 0000000..be30cf4 --- /dev/null +++ b/Functions/func.b @@ -0,0 +1,38 @@ +implement Func; + +include "sys.m"; +include "draw.m"; + +sys: Sys; +print: import sys; + +Func: module { + init: fn(nil: ref Draw->Context, nil: list of string); +}; + +plus: fn(a: int, b :int): int; + +plus(a: int, b: int): int { + return a + b; +} + +swp(a, b: int): (int, int) { + return (b, a); +} + +init(nil: ref Draw->Context, nil: list of string) { + sys = load Sys Sys->PATH; + + print("3 + 5 = %d\n", plus(3, 5)); + + print("7 + 3 + 4 = %d\n", plusplus(7, 3, 4)); + + (t₀, t₁) := swp(6, 7); + print("swap 6,7: %d,%d\n", t₀, t₁); + + exit; +} + +plusplus(a, b, c: int): int { + return plus(a, b) + c; +} diff --git a/README.md b/README.md index c0e2438..006feb1 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ You could then run said file with: - [If Else](./If-Else) - [Switch Case](./Switch) - [Arrays](./Arrays) +- [Functions](./Functions) ## References