July 8, 2020

Clojure Goodness: Replacing Characters In A String With escape Function

The clojure.string namespace contains a lot of useful functions to work with string values. The escape function can be used to replace characters in a string with another character. The function accepts as first argument the string value and the second argument is a map. The map has characters as key that need to be replaced followed by the value it is replaced with. For example the map {\a 1 \b 2} replaces the character a with 1 and the character b with 2.

In the following example code we use the escape function in several cases:

(ns mrhaki.string.escape-string
  (:require [clojure.string :as str]
            [clojure.test :refer [is]]))

(is (= "I 10v3 C10jur3"
       (str/escape "I love Clojure" {\o 0 \e 3 \l 1})))

(is (= "mrHAKI" 
       (str/escape "mrhaki" {\h "H" \a "A" \k "K" \i "I" \x "X"})))

(def html-escaping {(char 60) "<" (char 62) ">" (char 38) "&"})
(is (= "<h1>Clojure & Groovy rocks!</h1>"
       (str/escape "<h1>Clojure & Groovy rocks!</h1>" html-escaping)))

(is (= "Special chars: \\t \\n"
       (str/escape "Special chars: \t \n" char-escape-string)))

Written with Clojure 1.10.1.

July 5, 2020

Clojure Goodness: Concatenation Of Map Function Results With mapcat

When we use a function as argument for the map function that returns a collection we would get nested collections. If we want to turn the result into a single collection we can concatenate the elements from the collections by applying the concat function, but we can do this directly with the function mapcat. The function mapcat takes as first argument a function (that returns a collection) and one or more collections as next arguments.

In the following examples we see several uses of mapcat:

(ns mrhaki.core.mapcat
  (:require [clojure.test :refer [is]]))

;; The function argument for mapcat returns a collection
;; with the original element of the collection
;; and the value added by 10.
(is (= [1 11 2 12 3 13]
       (mapcat (fn [n] [n (+ 10 n)]) [1 2 3])))

(is (= [1 1 2 2 3 3]
       (mapcat (partial repeat 2) [1 2 3])
       ;; Using apply concat with map returns the same result.
       (apply concat (map (partial repeat 2) [1 2 3]))))

;; Combined with juxt
(is (= ["mrhaki" 6 "blog" 4]
       (mapcat (juxt identity count) ["mrhaki" "blog"])))

;; Our first example rewritten with juxt.
(is (= [1 11 2 12 3 13]
       (mapcat (juxt identity (partial + 10)) [1 2 3])))

;; We can use multiple collections,
;; the function then accepts multiple arguments.
(is (= [1 100 100 2 200 400 3 300 900]
       (mapcat (fn [a b] [a b (* a b)]) [1 2 3] [100 200 300])))

Written with Clojure 1.10.1.

July 2, 2020

Clojure Goodness: Creating Union Of Sets

When we are working with sets in Clojure we can use some useful functions from the clojure.set namespace. In a previous post we learned how we can get the difference of several sets. To get the union of several input sets we use the union function of the clojure.set namespace. The function returns a new set that is the union of unique elements from the input sets. A nil value is ignored by the union function.

In the following example code we use union:

(ns mrhaki.set.union
  (:require [clojure.set :as set]
            [clojure.test :refer [is]]))

;; union return a set with elements that contains the unique
;; elements of the input sets.
(is (= #{"Java" "Clojure" "Groovy" "Kotlin"}
      (set/union #{"Java" "Clojure" "Groovy"} #{"Kotlin" "Groovy" "Clojure"})))

;; We can use multiple input sets.
(is (= #{"Java" "Clojure" "Groovy" "Kotlin"}
       (set/union #{"Java" "Clojure" "Groovy"} 
                  #{"Groovy" "Clojure"}

;; A nil input is ignored.
(is (= #{"Clojure" "Groovy" "Kotlin"}
       (set/union #{"Groovy" "Clojure"} nil #{"Kotlin"})))

Written with Clojure 1.10.1.

June 29, 2020

Clojure Goodness: Find Differences In Sets

If we want to get the values from a set that are not part of one or more other sets we must use the difference function in the clojure.set namespace. The function returns a set with all values from the first set that are different from values in other sets.

In the following example we use the difference with several sets:

(ns mrhaki.set.difference
  (:require [clojure.set :as set]
            [clojure.test :refer [is]]))

;; The difference function will take a first set 
;; and leave out elements that are in the following set(s).
(is (= #{"Java"}
       (set/difference #{"Java" "Clojure" "Groovy"} 
                       #{"Kotlin" "Groovy" "Clojure"})))

(is (= #{"Java"}
       (set/difference #{"Java" "Clojure" "Groovy"} 
                       #{"Kotlin" "Groovy"} 

;; When other sets do not contain values
;; from the first set, the result is the original set.
(is (= #{1 2 3}
       (set/difference #{1 2 3} #{4 5})))

Written with Clojure 1.10.1.

June 25, 2020

Clojure Goodness: Keyword As Function

In Clojure functions are everywhere. In a previous post we learned that sets can be functions, but Clojure also makes keywords functions. A keyword is a symbol starting with a colon (:) and is mostly used in map entries as key symbol. The keyword as function accepts a map as single argument and returns the value for the key that equals the keyword in the map or nil if the keyword cannot be found.

In the following code we use keywords as function in several examples:

(ns mrhaki.core.keyword-function
  (:require [clojure.test :refer [is]]))

;; Sample map to use in examples.
(def user {:name "Hubert" :alias "mrhaki" :living {:country "Netherlands"}})

;; Keyword is a function with a map argument and
;; returns value for keyword in the map.
(is (= "mrhaki" 
       (:alias user)
       ;; We get the same result with get.
       (get user :alias)))

(is (= {:country "Netherlands"} (:living user)))

(is (= "Netherlands"
       (:country (:living user))
       (-> user :living :country)
       ;; We can use get-in to get values from nested maps.
       (get-in user [:living :country])))

;; When keyword is not in the map we get a nil result.
(is (nil? (:city user)))
(is (= "not-found" (or (:city user) "not-found")))

;; Works also for namespaced keywords.
(is (= "mrhaki" (:user/alias {:name/full-name "Hubert" :user/alias "mrhaki"})))

;; Using keyword as function with juxt.
(is (= ["mrhaki" "Hubert"] 
       ((juxt :alias :name) user)))

Written with Clojure 1.10.1.

June 19, 2020

Clojure Goodness: Using Sets As Functions

One of the nice things in Clojure is that some data structures are also functions. For me this felt rather strange when learning Clojure (coming from Java), but it can be very powerful. A set in Clojure is also a function. The set as function accept a single argument and it return nil when the argument is not part of the set, otherwise the argument value is returned. This behaviour also makes a set as function a nice predicate to be used for example in collection functions.

In the following example code we use different sets as function:

(ns mrhaki.set.function
  (:require [clojure.test :refer [is]]))

;; Sample set with some JVM languages.
(def languages #{"Clojure" "Groovy" "Kotlin"})

;; We can use the set languages as function
;; with one argument to check if the argument
;; is part of the set.
(is (= "Clojure" (languages "Clojure")))

;; If the argument is not part of the set
;; we get back nil.
(is (= nil (languages "Java")))

;; As nil is logical false in Clojure 
;; a set makes a nice predicate.
(is (= ["Clojure"] (filter #{"Clojure" "Java"} languages)))
(is (= ["Kotlin" "Groovy"] (remove #{"Java" "Clojure"} languages)))

;; Sample vector with numbers.
(def numbers [0 2 1 4 2 3 1 0])

;; Use set as predicate.
(is (= [2 1 2 1] (filter #{1 2} numbers)))

;; As set #{1 2} is a function we can use it as argument
;; for other functions to create a new function.
(is (= [0 4 3 0] (filter (complement #{1 2}) numbers)))

Written with Clojure 1.10.1.

June 15, 2020

Clojure Goodness: Create New Function Complementing Other Function

The Clojure function complement can be used to created a new function that returns the opposite truth value of the old function. The new function accepts the same number of arguments as the old function. Also when we invoke the new function created by the complement the old function is actually invoked and the result is used as argument for the not function to return the opposite truth value. So if the original function returns false or nil the result for the new function is true.

In the following example code we create a new function bad-weather that is the complement of good-weather:

(ns mrhaki.core.complement
  (:require [clojure.test :refer [is]]))

;; List with some temperatures for dates.
(def weather [{:date #inst "2020-06-05" :temperature 21}
              {:date #inst "2020-06-06" :temperature 17}
              {:date #inst "2020-06-07" :temperature 19}
              {:date #inst "2020-06-08" :temperature 25}
              {:date #inst "2020-06-09" :temperature 26}])

(defn good-weather
  "'Good' weather is when the temperature is between 20 and 30 degrees Celcius."
  [{temp :temperature}]
  (< 20 temp 30))

;; The opposite can easily be turned into a 
;; new function with complement. 
;; The bad-weather takes the same argument (temperature)
;; and returns false when good-weather would return true
;; and true when good-weather returns false.
(def bad-weather (complement good-weather))

(is (= [{:date #inst "2020-06-05" :temperature 21}
        {:date #inst "2020-06-08" :temperature 25}
        {:date #inst "2020-06-09" :temperature 26}]
       (filter good-weather weather)))

(is (= [{:date #inst "2020-06-06" :temperature 17}
        {:date #inst "2020-06-07" :temperature 19}]
       (filter bad-weather weather)))

;; Filtering on the good-weather and complement bad-weather
;; should return the same number of items as in the original collection.
(is (= 5
       (count weather)
       (count (concat (filter good-weather weather) (filter bad-weather weather)))))

Written with Clojure 1.10.1.

June 11, 2020

Java Joy: Reapply Function With Stream iterate

In Java we can use the iterate method of the Stream class to create an unbounded stream based on function invocations. We pass to the iterate method an initial value and a function that can be applied to the value. The first element in the unbounded stream is the initial value, the next element is the result of the function invocation with as argument the value from the previous element and this continues for each new element. Suppose we have a function expressed as lambda expression i -> i + 2. When we use this lambda expression with the iterate method and a initial value of 1 we get a stream of 1, 1 -> 1 + 2, 3 -> 3 + 2, ....

As we get an unbounded stream we must for example use limit to get the values we want from the stream. But we can also use an extra argument for the iterate method that is a Predicate definition. The iterate method will provide elements as long as the result of the Predicate is true. This way we the result of the iterate method is a bounded stream.

In the following Java example we use the iterate method with different arguments and lambda expressions:


import java.math.BigInteger;
import java.util.List;
import java.util.function.UnaryOperator;

import static;

public class Iterate {

    public static void main(String[] args) {
        // Create unbounded stream with odd numbers.
        var odds = Stream.iterate(1, i -> i + 2);

        // We use limit(5) to get the first 10 odd numbers from the unbounded stream.
        assert odds.limit(5).collect(toUnmodifiableList()).equals(List.of(1, 3, 5, 7, 9));

        // Create stream with even numbers, but here we use a predicate as
        // second argument to determine that we stop after value 10.
        var evens = Stream.iterate(0, i -> i <= 10, i -> i + 2);
        assert evens.collect(toUnmodifiableList()).equals(List.of(0, 2, 4, 6, 8, 10));

        // Define infinite stream with growing string.
        // The first element is ar, next argh, then arghgh etc.
        var pirate = Stream.iterate("ar", s -> s + "gh");

        // We get the 5-th element for a crumpy pirate.
        var crumpyPirate = pirate.skip(4).findFirst().get();
        assert crumpyPirate.equals("arghghghgh");

        // Function that returns the given amount
        // plus interest of 1.25%.
        UnaryOperator<Double> cumulativeInterest = amount -> amount + (amount * 0.0125);

        // Lazy sequence where each entry is the
        // cumulative amount with interest based
        // on the previous entry.
        // We start our savings at 500.
        var savings = Stream.iterate(500d, cumulativeInterest);

        // First element is start value, so we skip first five elements
        // to get value after 5 years.
        assert savings.skip(5).findFirst().get() == 532.0410768127441;

        // Define infinite unbounded stream
        // where each element is the doubled value of the previous element.
        var wheatChessboard = Stream.iterate(BigInteger.valueOf(1), value -> value.add(value));

        // Sum of all values for all chessboard squares is an impressive number.
        var square64 = wheatChessboard.limit(64).reduce(BigInteger::add).get();
        assert square64.equals(new BigInteger("18446744073709551615"));

Written with Java 14.

June 10, 2020

Java Joy: Infinite Stream Of Values Or Method Invocations

In Java we can use the generate method of the Stream class to create an infinite stream of values. The values are coming from a Supplier instance we pass as argument to the generate method. The Supplier instance usually will be a lambda expression. To give back a fixed value we simply implement a Supplier that returns the value. We can also have different values when we use a method that returns a different value on each invocation, for example the randomUUID method of the UUID class. When we use such a method we can create the Supplier as method reference: UUID::randomUUID.

The generate method returns an unbounded stream. We must use methods like limit and takeWhile to get a bounded stream again. We must use findFirst or findAny to terminate the unbounded stream and get a value.

In the following example we use the generate method with a Supplier that returns a repeating fixed String value and some different values from invoking the now method of LocalTime:


import java.time.LocalTime;
import java.util.List;

import static;

public class Generate {
    public static void main(String[] args) {
        // Create a infinite stream where each item is the string value "Java".
        // We let the supplier function return a fixed value "Java".
        assert Stream.generate(() -> "Java")
                     .collect(toUnmodifiableList()).equals(List.of("Java", "Java", "Java", "Java"));

        // Create an infinite stream of function invocations of
        // The supplier function returns a different value for each invocation.
        var currentTimes = Stream.generate(LocalTime::now)
        assert currentTimes.get(0).isBefore(currentTimes.get(1));

        // Create a list of 100 time values where each value should be later than the next.
        var timeSeries = Stream.generate(LocalTime::now).limit(100).collect(toUnmodifiableList());
        assert latestTime(timeSeries).equals(timeSeries.get(timeSeries.size() - 1));

     * Get the latest time from a serie of time values.
     * @param times List with time values.
     * @return Latest time value from the collection.
    private static LocalTime latestTime(List<LocalTime> times) {
        return, time) -> {
            if (acc.isAfter(time)) { return acc; } else { return time; }

Written with Java 14.

June 8, 2020

Clojure Goodness: Transforming Collection Items With Index

If we want to transform items in a collection we can use the map function. If we also want to use the index of the element in the collection in the transformation we must use the map-indexed function. We must provide a function with 2 arguments, where the first argument is the index of the element in the collection and the second argument is the element in the collection.

In the following examples we use the map-indexed function:

  (:require [clojure.test :refer [is]]))

;; map-indexed applies a function to each element
;; in a collection where the function gets the
;; index of the item in the collection and the item itself.
(is (= [[0 3] [1 20] [2 10] [3 2] [4 1]]
       (map-indexed (fn [index number] [index number]) [3 20 10 2 1])))

(defn indices
  "Return lazy sequence of indices of elements in a collection."
  (map-indexed (fn [index _] index) coll))

(is (= [0 1 2 3 4] (indices [3 20 10 2 1])))

(defn char-range
  "Function to return a range of characters from `start` to `end` (including)."
  [start end]
  (map char (range (int start) (inc (int end)))))

(def a-z (char-range \a \z)) ;; characters from a to z.

;; map-indexed returns a lazy sequence.
(is (= [[\a 0] [\b 1] [\c 2]]
       (take 3 (map-indexed (fn [index ch] [ch index]) a-z))))

;; Create map with letter keys and position in alphabet as values.
(def letters-positions (into {} (map-indexed (fn [index ch] [ch (inc index)]) a-z)))

(is (= [[\a 1] [\b 2] [\c 3]]
       (take 3 letters-positions)))

;; Find position of each letter of word "clojure".
(is (= [3 12 15 10 21 18 5]
       (reduce (fn [result value] (conj result (get letters-positions value)))

Written with Clojure 1.10.1.