5

In clojure I can use defnk to get named parameters. How can I achieve the same thing in ClojureScript?

Brian Knoblauch
  • 20,639
  • 15
  • 57
  • 92
yazz.com
  • 57,320
  • 66
  • 234
  • 385
  • Possible duplicate of [Clojure - named arguments](https://stackoverflow.com/questions/3337888/clojure-named-arguments) – Erik Kaplun Aug 02 '19 at 15:04

1 Answers1

11

The named args functionality in ClojureScript is the same as in Clojure:

(defn f [x & {:keys [a b]}] 
  (println (str "a is " a " and b is " b)))

(f 1)
; a is  and b is 

(f 1 :a 42)
; a is 42 and b is 

(f 1 :a 42 :b 108)
; a is 42 and b is 108

If you want default values, then change the original to:

(defn f [x & {:keys [a b] :or {a 999 b 9}}]
  (println (str "a is " a " and b is " b)))

(f 1)
; a is 999 and b is 9

This is related to the nice answer for Clojure - named arguments

Community
  • 1
  • 1
fogus
  • 6,126
  • 5
  • 36
  • 42
  • Thanks for the answer. But now I'm really confused. Why has defnk been put into Clojure then? – yazz.com Jan 03 '12 at 19:04
  • There's no such thing in clojure by default. It may be included in clojure.contrib (don't know if it is), but such macro doesn't exist in standard clojure library. – Vladimir Matveev Jan 03 '12 at 20:07
  • 3
    `defnk` is defined in clojure.contrib. It was created before Clojure 1.2 added full map destructuring binding. `defnk` should now be considered obsolete (indeed the monolithic clojure.contrib isn't compatible with Clojure 1.3 going forward.) – Alex Stoddard Jan 19 '12 at 22:03
  • is there a way to use a keyword argument like :do-logs and then use something like (when do-logs ...) within the body? – wirrbel Mar 11 '13 at 10:45