-- 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
new[] {1, 2, 3}.Zip(new[] {10, 20, 30}, (x, y) => x + y); | |
// { 11, 22, 33 } |
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.