← Back to home

Moving points with merge-with

I saw an example of doing a move operation on a set of points using merge-with in Clojure the other day.

Say, you have a triangle in a 2D space, represented by a list of points:

user=> (def points '({:x 10 :y 10} 
                     {:x 15 :y 17}
                     {:x 25 :y 30}))
#'user/points

And then you’d like to move them all ten ticks to the right:

user=> (map #(merge-with + {:x 10} %) points)
({:x 20, :y 10} {:x 25, :y 17} {:x 35, :y 30})

And that’s it. No loops, no imports of specific modules to deal with geometry, no custom types, function or operators. It’s just the most vanilla Clojure one can possibly imagine. I just can’t get my head around of how elegantly it allowed me to express this idea.

This is the point where I would probably be very excited and eager to learn math during my university years. What other concepts from algebra and geometry are present there in functional programming, just perhaps they are named a bit differently? However, making websites and playing music was more appealingto me back then, so I wasn’t as excited.

This blogpost is dedicated to Martin who promised me to read it the next day at 06:30 in the morning. See, Martin, I wrote it. And yes, I’ve changed the publishing date :)