On 2 авг, 04:47, Brad <b...@beaconhill.com> wrote: > I wanted to take a Map and convert it to a string suitable for use as > parameters in a URL. I have got it working below two different ways > but wondered if there was a better or more idiomatic way to do this. > > ;; My test input map > (def input {:a 1 :b 2 :c 3 :d 4}) > > ;; What I'd like the input map convert into. A string that looks like > keyword=value&keyword=value&, .... > (def output "a=1&b=2&c=3&d=4") > > ;; This function converts each MapEntry to the key=value > (defn map-entry-to-string-pair > "Convert a key value from a map into a string that looks like > key=value. > For example, > (def input {:a 1 :b 2 :c 3 :d 4}) > (map-entry-to-string-pair (first input)) => \"a=1\"" > [mapentry] > (str (name (first mapentry)) "=" (second mapentry))) > > ;; The following two functions build the result string. There is not > much of a difference between them. The first uses > ;; let to hold a variable after mapping map-entry-to-string-pair over > the input map. The other just uses the same mapping > ;; after converting it to a vector. > > (defn convert-map-to-url-string1 > "Convert a map from keyword values to a string that consists of > keyword=value pairs separated by &s for use in a URL > For example, > (def input {:a 1 :b 2 :c 3 :d 4}) > (convert-map-to-url-string1 input) => \"a=1&b=2&c=3&d=4\"" > [m] > (let [pairs (map map-entry-to-string-pair m)] > (join "&" pairs))) > > (defn convert-map-to-url-string2 > "Convert a map from keyword values to a string that consists of > keyword=value pairs separated by &s for use in a URL > For example, > (def input {:a 1 :b 2 :c 3 :d 4}) > (convert-map-to-url-string2 input) => \"a=1&b=2&c=3&d=4\"" > [m] > (join "&" (vec (map map-entry-to-string-pair m)))) > > Is there a simpler, better way to do this? > > - Brad
Also, you can use jaco's named routes to do this: (defroute simple "/foo/bar") (simple :baz "qux") => "/foo/bar?baz=qux" -- 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