I was in to process of writing a rant against condp when I realized I had
been thinking about it all wrong.  Here is what I wanted at first:

(defmacro casep [pred & clauses]
  `(condp #(%2 %1) ~pred ~...@clauses))

In other words, I want to be able to specify a unary predicate instead of a
binary predicate and a single argument for it.  I know from reading
discussions on clojure-dev that the main advantage of condp over casep is
that condp evaluates its first two arguments only once, and writing the same
code using casep would could cause a lot of redundant evaluation.  While I
agree that condp earns its keep on that basis, I was still annoyed by the
way condp calls the predicate you give it.  I was hoping that condp could
use an off-the-shelf function like apply, so I could get the effect of casep
just by writing code like (condp apply my-unary-predicate ...); IMHO this is
a perfectly readable idiom, but, alas, it's wrong; in place of apply, you
have to use something like #(%2 %1), which looks far too Perlish for my
taste.

The saving grace of condp is that there are a lot more useful binary
predicates than I had realized at first. When I went back and re-examined
some of my code, I found you can do some cool things with condp that would
not be possible if condp passed the arguments to the predicate in a
different order:

;; Which value is less then 3?
(condp < 3
  x ...
  y ...
  z ...)

;; Which set contains x?
(condp contains? x
  set-a ...
  set-b ...
  set-c ...)

;; Which object (represented as a map) is flagged as special?
(condp get :special?
  map-a ...
  map-b ...
  map-c)

;; Which predicate does x satisfy?
(condp apply [x]
  integer? ...
  string? ...
  nil? ...)

Even a use case that's tailor-made for casep is not so bad if you're willing
to turn the test expressions into functions:

;; Which item satisfies my-pred?
(condp apply [my-pred]
  #(% item-a) ...
  #(% item-b) ...
  #(% item-c) ...)

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to