1

In Clojure, what is the idiomatic way to validate that a value is one of a set of possible values?

I initially did something like this:

(let [size :grande]
  (make-latte (condp = size
                :tall :tall
                :grande :grande)))

The above is useful because if no clause matches an IllegalArgumentException is thrown.

But then I found this more comfortable to do:

(let [size :grande]
  (make-latte (or (some #{:tall :grande} [size])
                  (throw (IllegalArgumentException. "I don't know that size")))

This technique works well because it allows for more possible values, e.g.

(some #{:short :tall :grande :venti} [size])

What's the best way to do this? Am I right in thinking that clojure.core does not have a function that does this already?

pestrella
  • 9,786
  • 4
  • 39
  • 44

2 Answers2

9

(some #{:short :tall :grande :venti} [size])

is equivalent to

(#{:short :tall :grande :venti} size)

That's because sets are functions. For a generic collection you can use contains?.

Edit: as user1571406 notes below, be aware that contains? tests for keys, not values.

Diego Basch
  • 12,764
  • 2
  • 29
  • 24
  • 1
    Although do note that `contains?` checks whether the value is a **key** in an associative collection. So `#{:venti :grande} contains? :venti` and `:grande` but `[:venti :grande]` will `contains?` *0 and 1*. – Magos Jan 27 '15 at 04:20
0

You could use a pre-condition in the make-latte function itself. See https://stackoverflow.com/a/8607359/609639

Community
  • 1
  • 1
TheQuickBrownFox
  • 10,544
  • 1
  • 22
  • 35