siyu798 <siyu...@gmail.com> writes: Hi Siyu,
> Your with-default fn is neat. So it appears there's no > idiomatic/built-in clojure fn/macro to do parsing and wrapper > functions such as follow would be needed to avoid typing the whole > expression every time. > > (def parse-double (with-default #(Double. %) 0.0)) > (def parse-int (with-default #(Integer. %) 0)) You could pass the desired wrapper class as an argument to the function and use reflection to create a new instance. I think all wrapper classes have a constructor for parsing an String. Then you could write (parse-wrapper Integer "111" 42) ==> 111 (parse-wrapper Double "111.1" 42.2) ==> 111.1 (parse-wrapper Byte "257" 42.2) ==> 42.3 Here's a (not really tested) version: --8<---------------cut here---------------start------------->8--- (defn parse-wrapper [c v & [d]] (try (-> c (.getConstructor (into-array Class [String])) (.newInstance (into-array Object [v]))) (catch Throwable _ d))) --8<---------------cut here---------------end--------------->8--- Well, that doesn't save you much... --8<---------------cut here---------------start------------->8--- (map #(parse-wrapper Double % 42.2) ["0" "1.5" "3.8e-1" "broken" "0x1.bP2" "Infinity" "NaN"]) ==> (0.0 1.5 0.38 42.2 6.75 Infinity NaN) --8<---------------cut here---------------end--------------->8--- And maybe it's a bit slower due to the use of reflection... Bye, Tassilo -- 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