Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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 ?

like image 911
Marcus Junius Brutus Avatar asked Feb 09 '13 20:02

Marcus Junius Brutus


1 Answers

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)
like image 149
A. Webb Avatar answered Sep 30 '22 20:09

A. Webb