DEV Community

loading...
Cover image for Creating our own map in Clojure on the nail πŸ‘©β€πŸ­πŸ‘¨β€πŸ­

Creating our own map in Clojure on the nail πŸ‘©β€πŸ­πŸ‘¨β€πŸ­

wakeupmh profile image Marcos Henrique ・2 min read

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 πŸ€—

Discussion

pic
Editor guide