I had a pattern that kept popping up in code of:

(let [x (foo)
      y  (bar)]
    (when y
       (let [ ....]
           ....)))

that check jarred me, so I put this together:
https://gist.github.com/1347312. On reflection, discomfort with indentation
levels probably isn't near the top of the "to macro or not to macro?"
checklist.

(defmacro let?
[bindings & body]
 (let [[bind [kwd pred & more]] (split-with (complement #{:ensure})
bindings)]
`(let [~@bind]
 ~@(cond (and kwd more) [`(when ~pred (check-let [~@more] ~@body))]
kwd [`(when ~pred ~@body)]
 :else body))))

(let? [x 100
y 300
 :ensure (pos? y)
z (- y 250)]
 z)

;; expands to

(let [x 100
y 300]
 (when (pos? y)
(let [z (- y 250)]
 z))) ;; => 50

;; and returns 50. The following returns nil:

(let? [x 100

       y 300

       :ensure (neg? y)

       z (- y 250)]
      z) ;; => nil


On Tue, Dec 6, 2011 at 11:51 AM, Evan Gamble <[email protected]> wrote:

> I noticed in my code that I often nest a let inside an if-let, or vice-
> versa, so I wrote a macro let-else that expands into nested lets,
> except where there's an :else <expr> after a binding, in which case
> that binding expands into an if-let.
>
> E.g.
>
> (let-else
>  [foo (f1) :else (e)
>   bar (f2)]
>  (b1)
>  (b2))
>
> expands into
>
> (if-let [foo (f1)]
>  (let [bar (f2)]
>    (b1)
>    (b2))
>  (e))
>
> The jar is at https://clojars.org/org.clojars.egamble/let-else
> The code is at https://github.com/egamble/let-else
>
> - Evan
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to [email protected]
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> [email protected]
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en




-- 
Sam Ritchie, Twitter Inc
703.662.1337
@sritchie09

(Too brief? Here's why! http://emailcharter.org)

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

Reply via email to