DEV Community is a community of 783,060 amazing developers

We're a place where coders share, stay up-to-date and grow their careers. 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])

The native map 👴

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

(map println values)
;this will print each value

Our own map 😎

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

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))

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))

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 🤗 