documenting defn / defun

This commit is contained in:
Tuukka Turto 2013-08-05 23:23:35 +03:00
parent 635e47b2cb
commit 7709509ed3

View File

@ -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
--------