From 7709509ed3a0669d215d4e80213a77da817ea27e Mon Sep 17 00:00:00 2001 From: Tuukka Turto Date: Mon, 5 Aug 2013 23:23:35 +0300 Subject: [PATCH] documenting defn / defun --- docs/language/api.rst | 58 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/docs/language/api.rst b/docs/language/api.rst index 3f0a8ca..fc5c99f 100644 --- a/docs/language/api.rst +++ b/docs/language/api.rst @@ -298,6 +298,64 @@ parameters: `name` of the function to define, vector of `parameters` and the (defn name [params] body) +Parameters may have following keywords in front of them: + +&optional + parameter is optional. The parameter can be given as a two item list, where + the first element is parameter name and the second is the default value. The + parameter can be also given as a single item, in which case the default + value is None. + + .. code-block:: clj + + => (defn total-value [value &optional [value-added-tax 10]] + ... (+ (/ (* value value-added-tax) 100) value)) + + => (total-value 100) + 110.0 + + => (total-value 100 1) + 101.0 + +&key + + +&kwargs + parameter will contain 0 or more keyword arguments. + + The following code examples defines a function that will print all keyword + arguments and their values. + + .. code-block:: clj + + => (defn print-parameters [&kwargs kwargs] + ... (for [(, k v) (.items kwargs)] (print k v))) + + => (kwapply (print-parameters) {"parameter-1" 1 "parameter-2" 2}) + parameter-2 2 + parameter-1 1 + +&rest + parameter will contain 0 or more positional arguments. No other positional + arguments may be specified after this one. + + The following code example defines a function that can be given 0 to n + numerical parameters. It then sums every odd number and substracts + every even number. + + .. code-block:: clj + + => (defn zig-zag-sum [&rest numbers] + (let [[odd-numbers (list-comp x [x numbers] (odd? x))] + [even-numbers (list-comp x [x numbers] (even? x))]] + (- (sum odd-numbers) (sum even-numbers)))) + + => (zig-zag-sum) + 0 + => (zig-zag-sum 3 9 4) + 8 + => (zig-zag-sum 1 2 3 4 5 6) + -3 defmacro --------