I know at a certain point in my code that a list only has one element so I obtain it with
(first alist)
But I would also like the code to break if the list has more than one elements to alert me of the erroneous condition. What's an idiomatic way to achieve that in Clojure ?
Replace first
with an only
(or other poetically named) function with a pre-condition where you want to make your assertion:
(defn only [x] {:pre [(nil? (next x))]} (first x))
(only [1])
=> 1
(only [1 2])
=> AssertionError Assert failed: (nil? (next x)) user/only (NO_SOURCE_FILE:1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With