Create Clojure Map, advanced methods, PART 2
Let’s continue our journey of functions that return maps.
For those missed the first chapters:
In this chapter I am going to talk about, bean
, frequencies
, group-by
and finally clojure.set/index
.
Let’s start with
bean
if you don’t take advantage of the clojure compatibility with java, bean
is quite useless to you. However if you do import java libraries in your clojure code bean
can be one of your best friends.
Given a java object, bean
returns a “map” that represents such object.
The best example I could figure out is the one from the clojure doc.
Please, be very careful here.
What bean returns is not an actual map but something more complex that implements the map protocol.
What you need to know is that changing the underneath original object will do change the “map” that bean
returns, so be very careful.
frequencies
As the name suggests, given a sequence, frequencies
returns a map with the frequency of each object in the sequence itself.
If you have understood frequencies
group-by
is similar. Let me show you a simple example.
As you can see group-by
calls the function you provide for every element in the sequence. It stores the output as a key and, as a value, the collection of those elements who returns the same output.
clojure.set/index
This function is a little complex.
First and foremost we are working with sets, as you may know sets are collections of unique unordered elements.
It is very fast to add element to a set or to check if an element is in the set.
Of course sets may also contain maps.
If I have a big set of maps I may want to explore those maps more deeply and I may need to aggregate together all the maps with the same value for some particular key, this is clojure.set/index
.
index
is very complex to explain thus I am afraid that I would create more confusion than other trying to word what you can see in action.
If you aren’t completely sure about index
you may try to run the function inside a repl: maybe a bigger and more etereogeneous map will help.
As always if you have any question please write a comment bellow.
End
This chapter was very short and probably somehow boring, but it was necessary for the sake of completeness.
Next time we are moving on to something way more fun and useful.
Next Chapter, Read Clojure Map overview of: get, get-in, contains? and find
As always, stay tuned and write to me if you have anything to say (Ex. Some question, a request for an article, anything…)