Search code examples
clojure

Clojure :: get the single element of a list and throw exception if the list has more than 1 elements


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 ?


Solution

  • 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)