Named parameters: Difference between revisions

Content added Content deleted
(→‎{{header|XSLT}}: Added omit PureBasic)
Line 133: Line 133:
Clojure doesn't have built-in support for named or keyword arguments, but you can use destructuring to achieve a similar effect.
Clojure doesn't have built-in support for named or keyword arguments, but you can use destructuring to achieve a similar effect.


<lang lisp>(defn foo [& opts]
<lang clojure>(defn foo [& opts]
(let [opts (merge {:bar 1 :baz 2} (apply hash-map opts))
(let [opts (merge {:bar 1 :baz 2} (apply hash-map opts))
{:keys [bar baz]} opts]
{:keys [bar baz]} opts]
[bar baz]))</lang>
[bar baz]))</lang>

Clojure 1.2 supports destructuring of trailing arguments as a map:

<lang clojure>(defn foo [& {:keys [bar baz] :or {bar 1, baz 2}}]
[bar baz])</lang>


You can also use <code>defnk</code> from <code>clojure.contrib.def</code>, which is a macro that works similarly.
You can also use <code>defnk</code> from <code>clojure.contrib.def</code>, which is a macro that works similarly.


<lang lisp>(use 'clojure.contrib.def)
<lang clojure>(use 'clojure.contrib.def)
(defnk foo [:bar 1 :baz 2]
(defnk foo [:bar 1 :baz 2]
[bar baz])</lang>
[bar baz])</lang>


Sample output for both:
Sample output for all variants:


<pre>user> (foo :baz 123)
<pre>user> (foo :baz 123)