DEV Community

Cover image for Creating our own map in Clojure on the nail 👩‍🏭👨‍🏭
Marcos Henrique
Marcos Henrique

Posted on

Creating our own map in Clojure on the nail 👩‍🏭👨‍🏭

Prologue 🧐

In many programming languages, map is the name of a higher-order function that applies a given function to each element of a functor, a list, returning a list of results in the same order. It is often called apply-to-all when considered in functional form.

The concept of a map is not limited to lists: it works for sequential containers, tree-like containers, or even abstract containers such as futures and promises.

let's assume we have an array with 5 values

(def values [22 33 11 23 15])
Enter fullscreen mode Exit fullscreen mode

The native map 👴

This way we will apply the native form to iterate the values

(map println values)
;this will print each value
Enter fullscreen mode Exit fullscreen mode

Our own map 😎

(defn my-map 
    [function sequence]
    (let [firsElement (first sequence)]
        (if firsElement
            (do
                (function firsElement)
                (my-map function (rest sequence))))))
Enter fullscreen mode Exit fullscreen mode

Now we can use our map to iterate or pass any function to do something, let's implements an example, calculate the square of each element 🤓

(defn my-map 
    [function sequence]
    (let [firsElement (first sequence)]
        (if firsElement
            (do
                (function firsElement)
                (my-map function (rest sequence))))))

(defn square [value] (* value value))

(println (my-map square value))
Enter fullscreen mode Exit fullscreen mode

But if we have thousand of elements this possible throw a stackoverflow exception because normal recursion is a call stack, and a stack can be fully populated 😅

The ninja way (who prevents stackoverflow exception)🐱‍👤

Tail Recursion

In clojure the recur is a way to transform a recursion into a otimized loop, for this purpose is the best way

(defn my-map 
    [function sequence]
    (let [firsElement (first sequence)]
        (if firsElement
            (do
                (function firsElement)
                (recur function (rest sequence))))))

(defn square [value] (* value value))

(println (my-map square value))
Enter fullscreen mode Exit fullscreen mode

Just for today, feel free to comment, I'm still learning and I usually share whenever I can, because I'm adept at learning public 🤗

Top comments (0)