On Sat, Apr 20, 2013 at 12:47 PM, Cedric Greevey <cgree...@gmail.com> wrote:
> On Sat, Apr 20, 2013 at 5:15 AM, Ken Scambler <ken.scamb...@gmail.com>wrote: > >> Hi there, >> I'm getting started with Clojure, and found myself really missing >> Scala-style pattern matching. Now I know about Matchure and core.match, >> but all I really needed was a cond using test predicates rather than >> boolean expressions, like this: >> >> (condval value >> foo-pred? (foo-result) >> bar-pred? (bar-result) >> else? (default-result)) >> >> (Where 'else? is a predicate that ignores the argument and returns true) >> >> Lisp being Lisp, I rolled my own and it works fine. >> > > How different was what you came up with from this? > > (def else? (constantly true)) > > (defmacro condval [vname & body] > `(cond > ~@(interleave (map (fn [p] `(~p ~vname)) (take-nth 2 body)) > (take-nth 2 (rest body))))) > > Just out of curiosity. :) > Huh. Now that I think of it, the pattern of transforming every second item in a list is fairly often recurring, particularly (though not exclusively) in macro writing (mainly because of things like cond, bindings, and such that alternate two types of item, with dissimilar roles, in a sequential). And that, in turn, suggests (defn multimap [coll f & fs] (map #(%1 %2) (cycle (cons f fs)) coll)) and, of course, (defmacro condval [vname & body] `(cond ~@(multimap body (fn [p] `(~p ~vname)) identity))) (Incidentally, did you know that (take-nth 0 foo) will hang rather than throw an exception? In fact, it returns an infinite lazy seq of the first element of foo repeated forever, if foo isn't empty, but trying to print this result hangs the REPL. Weirder, (take-nth -1 foo) will do the same thing, rather than walk backwards off the near end of foo and throw an IndexOutOfBoundsException when, say, foo is a vector. -- -- 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 --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/groups/opt_out.