Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Mandatory keyword argument

I have a function like this:

(defn foo [{a :keya b :keyb}]
  (list a b))

And i'm calling it like this:

(foo {:keya "hi"}) ; Returns ("hi" nil)

If I don't give keyb keyword argument, it takes nil for that. Is there a way to ensure that it throws exception for it instead of taking it as nil.

( I know that I can manually check and throw an exception, but is there any special option which enforces the constraints.)

like image 953
Sibi Avatar asked May 20 '26 23:05

Sibi


2 Answers

You can use a precondition (http://clojure.org/special_forms#toc9) to assert the key is present:

(defn foo [{a :keya b :keyb}] 
   {:pre [(not (nil? b))]}
   (list a b))

This will throw an AssertionError when the key is nil.

like image 120
aldazosa Avatar answered May 23 '26 14:05

aldazosa


No, but of course because Clojure is a lisp you can define your own macro that handles the boring "manual checking" for you automatically.

like image 30
amalloy Avatar answered May 23 '26 12:05

amalloy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!