wood burning stoves*
The moose likes Clojure and the fly likes how to implement : key + Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Languages » Clojure
Bookmark "how to implement : key + " = " + get(key)" Watch "how to implement : key + " = " + get(key)" New topic
Author

how to implement : key + " = " + get(key)

jay vas
Ranch Hand

Joined: Aug 30, 2005
Posts: 407
Hi guys :

Im (cursed me) thinkin in java again. I have a map

{a 1.0, b 2.0}

and I want to format the key value pairs, and then apply a function to the formatted pairs , i.e.



Is this the idiomatic way to process the key / value in a clojure via the fmap function ?
jay vas
Ranch Hand

Joined: Aug 30, 2005
Posts: 407
Ok, I found the solution to this. To iterate over keys and values of a map, you use the doseq function.

Doseq defines, as the first arg, the "type" of data that your iterator is generating, so for example, with a map , you have

(doseq [[k v] myMapGetter] #(println k v) )

It seems odd that [k v] are in scope however. how can the print statement see them ? They appear to be enclosed by ['s ?
Sean Corfield
Ranch Hand

Joined: Feb 09, 2011
Posts: 252
    
    5

That's called destructuring. Maps behave like sequences of vectors (with two elements - the key and the value). [k v] is a vector destructuring that binds k to the first element of the vector and v to the second element of the vector.

doseq is for when you're dealing with side effects. Normally you'd use map to apply a function to each element of a sequence: (map (fn [[k v]] (str k "=" v)) my-map) will produce the sequence ( "a=1.0" "b=2.0" ) based on your original data. You can turn that into a comma-delimited list with clojure.string/join: (clojure.string/join ", " (map (fn [[k v]] (str k "=" v)) my-map)).

BTW, you'll do better to try to work within the core language / libraries and avoid contrib if you can. The monolithic contrib of 1.2.0 is being broken up and only modules with active maintainers will go forward to 1.3.0 (new contrib modules are compatible with 1.2.0 and 1.3.0 so you can switch to the new modules first, then switch to 1.3.0). See Where did Clojure.Contrib go? for more details of the migration.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: how to implement : key + " = " + get(key)
 
Similar Threads
JSP Session Problem
Replace keycode value in Firefox
Groovy Script - Converting to UpperCase
jsp:useBean
reverse a map and sort