Collections

Clojure Goodness: Get Random Item From A Sequence

Posted on by  
Hubert Klein Ikkink

In Clojure we can use the rand-nth function to get a single random element from a sequence. To get multiple items based on random probability for each item we use the function random-sample. We must set the probability that determines for each item if it is in the result or not.

In the following example code we use rand-nth function:

Continue reading →

Clojure Goodness: Getting Intersections Between Sets

Posted on by  
Hubert Klein Ikkink

In the clojure.set namespace we can find the intersection function. This functions accepts one or more sets as arguments and return a new set with all elements that are present in the sets that are passed as arguments to the intersection function. The argument must be a set, so we need to convert other collection or seq values to a set first before we use it as an argument for the function.

In the following example we use one, two or three arguments for the intersection function and also convert other types to a set to be used as argument:

Continue reading →

Clojure Goodness: Joining Elements in a Collection

Posted on by  
Hubert Klein Ikkink

We can use the join function from the clojure.string namespace to join elements from a collection into a string. We can optionally specify a separator that is used to separate each element in the string output. The separator is not used after the last element of the collection. If we don’t specify a separator the elements are concatenated without separation. The string representation for each element in the collection is used in the joined end result.

In the following example code we see different usages of the join function:

Continue reading →

shadow-left