From 5a2bfb8f3be29025e188f6707044fa77e875f29b Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sun, 5 Oct 2014 20:32:39 -0400 Subject: [PATCH] more function docs --- functions.md | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/functions.md b/functions.md index d1157fb..e3f064e 100644 --- a/functions.md +++ b/functions.md @@ -13,8 +13,7 @@ could be assigned to a variable on the package using `def`, or by using the shortcut `defn`. The following two statements are equivalent: ``` - -(def incr +(. def incr (. fn [x] (: + x 1))) @@ -22,6 +21,46 @@ shortcut `defn`. The following two statements are equivalent: (: + x 1)) ``` +## Function returns + +### Single returns + +A function returns whatever the last expression in its execution returned. For +example: + +``` +(. defn abs [x] + (. if (: >= x 0) + x + (: * -1 x))) +``` + +This function will return the argument `x` if it is greater than or equal to 0, +or `(* -1 x)` if it's not. + +### Multiple returns + +A function which wishes to return multiple arguments should return them as a +vector or list of arguments. The `let` function, which can be used to define +temporary variables in a scope, can deconstruct these multiple-returns: + +``` +# Returns two numbers which sum up to 10 +(. defn sum-10 [] + [4 6]) + +(. let [[foo bar] (: sum-10) + (: fmt.Println "%d + %d = 10" foo bar)) +``` + +Functions defined within a go library which return multiple values can also be +deconstructed in a `let` statement: + +``` +(. let [[conn err] (: net.Dial "tcp" "localhost:80")] + # do stuff) +``` + ## Variadic function Functions may take in any number of variables using the `...` syntax, similar to