Sunday, March 15, 2015

Examples of Map as a Series of Applying a Function -- in Clojure and kind of in C#.

"It is now apparent?"
-- Shakespeare, Measure for Measure
Act IV, Scene II, Line 135

Every now and then you read something and think, that is exactly what I have been thinking to myself but could not find the words.  Such an experience happen to myself this week.

I was reading Clojure Programming by Chas Emerick, Brian Carper, and Christophe Grand and found exactly how I have been thinking about the higher order function map but have not been able to express in words properly (it is on page 62 in the first edition).

map f [a b c] can be expressed as [(f a) (f b) (f c)]

Likewise map f [a b c] [x y z] can be expressed as [(f a x) (f b y) (f c z)] and so on ...

So what would this look like in code?

Glad you asked.

(map + [1 2 3])
;; (1 2 3)
[(+ 1) (+ 2) (+ 3)]
;; [1 2 3]
(map + [1 2 3] [10 20 30])
;; (11 22 33)
[(+ 1 10) (+ 2 20) (+ 3 30)]
;; [11 22 33]
view raw repl.clj hosted with ❤ by GitHub
new[] {1, 2, 3}.Zip(new[] {10, 20, 30}, (x, y) => x + y);
// { 11, 22, 33 }
view raw repl.cs hosted with ❤ by GitHub


We see that in Clojure we can get exactly what we are looking for.  As a comparison we fins that in C# using the Zip we can get fairly close.