2010/1/2 Sean Devlin <francoisdev...@gmail.com>:
> I don't think your version of the signature supports variadic defaults well.

Hi Sean,

Thanks for commenting.

Just by way of clarification, taking the function as the last argument
seems to work fine in my experiments. I'm sure it could be better but
here what I've been using:

(defn fnil
  "Creates a new function that if passed nil as an argument,
  operates with supplied arguments instead. The function must be
  passed as the last argument."
  [& more]
  (fn [& m] (apply (last more)
                   (map #(if (nil? %1) %2 %1)
                        m
                        (concat (butlast more)
                                (drop (count (butlast more)) m))))))

Relating to your examples:
user=> (def nil+ (fnil 0 1 2 3 4 5 6 +))
user=> (nil+ 0 0 0 0 0 0 nil)
6
user=> (nil+ 0 0 0 0 0 0 0 nil)
java.lang.NullPointerException (NO_SOURCE_FILE:0)
user=> ((fnil 1 +) nil 2 3 4 5)
15

; note fnil-2 does not handle the last case, though of course it could
easily if you wanted it to:
user=> ((fnil-2 1 +) nil 2 3 4 5)
java.lang.ClassCastException: java.lang.Integer cannot be cast to
clojure.lang.IFn (NO_SOURCE_FILE:0)

; in principle I don't think one form is any more restrictive than the
other, it just comes down to a matter of preference which is the key
part I wanted to generate discussion about.


> matches the signature of partial better, which I personally prefer.

Yes that is precisely why it catches me out to write (fnil + 1)
because it looks like a partial application. Partial applications are
actually very common even when partial is not explicitly used:
user=> (swap! (atom 1) + 1)
2
So I'm used to seeing arguments to the right of a function get
absorbed so to speak, and used to seeing conditionals occur in the
middle of the form. Again just clarifying that I too like partial
application style but have the opposite reaction in this case of
wanting to contrast that for fnil as it is not a partial application.
This of course is just my preference and I'm glad to hear reasoning
for the other style.


Regards,
Tim.

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