Hi,
I want to share an idea I've been playing with recently.  I noticed I want
to convert between different representations of roughly the same value every
now and then, string to number, a var to symbol and vice versa, even a
filename to an open stream.  There are two approaches in the language.  The
one works only for collections, and in a not extensible way: (into {} coll)
to convert to a map, (into [] coll) to convert to a vector.

The other approach is to have a pair of lowercase functions for datatype
Foo, foo? checks if a value is foo, and (foo bar) converts bar to foo.  This
is not quite coherent, though.
 (set '(1 3)), but (apply vector '(1 3))
 (int 3.3), but (integer? 3.3)
 (str 3) => "3", but (int "3") => ClassCastException
 And there are the different functions to convert between a var, a symbol, a
fn -- well, I know it's not quite a conversion, but still, I think
it's unambiguous in some cases what a user would expect from such a
conversion.

My suggestion is a single multimethod that dispatches on the source type and
a target type:
(defmulti to (fn [target-type value] [target-type value]))

Then we can have some implementations
(defmethod to [Integer String] [s _] (try (Integer/parseInt s) (catch
NumberFormatException e nil)))
(defmethod to [String Integer] [i _] (str i))
etc

and we can simply use (to Integer "3")
Besides simplicity, this would be more easily extensible, so it would fit
nicely into some c.c.generic namespace.

What do you think?

Adam

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