On Mar 19, 2:27 am, Ken Wesson <[email protected]> wrote:
> On Fri, Mar 18, 2011 at 1:13 PM, Shantanu Kumar
>
> <[email protected]> wrote:
> > The `try-times` macro above is buggy (doesn't work when body of code
> > returns logical false). Fixed version is below:
>
> > (defmacro try-times
> >  [n & body] {:pre [(posnum? n)]}
> >  `(let [c# (repeat-exec (dec ~n) #(maybe ~@body))
> >         r# (some #(if (last %) nil %) c#)]
> >     (first (or r# [(do ~@body)]))))
>
> You might want to unwrap everything after:
>
> (defmacro try-times
>   [n & body] {:pre [(posnum? n)]}
>   `(let [c# (repeat-exec (dec ~n) #(maybe ~@body))
>          r# (some #(if (last %) nil %) c#)
>          [r# e#] (first (or r# [(do ~@body)]))]
>      (if e#
>        (throw e#)
>        r#)))
>
> This will re-throw the last exception on failure. On success it will
> evaluate to the return value of the successful execution of the body.
> So this try-times trying to acquire a network socket may throw a
> socket unavailable exception or return the socket, rather than
> returning a vector of a maybe-socket and a maybe-exception.

My version already does that if I understand correctly. Ken Wesson's
variation on `delay` is neat.

I came up with another way to retry on exception:

(defmacro try-while
  "Return the result after executing code body; on exception keep re-
trying as
  long as pred returns true. The predicate function accepts thrown
exception
  as argument. Unless pred throws an exception, no exception will
escape the
  code body itself."
  [pred & body] {:pre [`(fn? ~pred)]}
  `(first (some #(let [e# (last %)]
                   (if e# (if (~pred e#) false
                            (throw e#))
                     %))
            (repeat-exec #(maybe ~@body)))))

Regards,
Shantanu

-- 
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