I've now finished 66 / 156 problems on 4clojure!
I'm coming to understand one of the powerful features of Clojure, and Lisp languages in general, is the interchangeability between code and data. That Clojure code is itself a data structure allows programmers to extend the language through use of macros. There are also cases where data structures can themselves be treated as functions.
Example. In "Set Intersection", the challenge is to re-implement set intersection with out using the
intersection function. This means that, given two sets, find the elements that are present in both. The straightforward imperative algorithm may be to iterate over the first set and simply add items to a new set when also present in the second.
# pseudocode s = new Set for item in set1 do if set2 contains? item do s add item end end s
In Clojure, we can pass a function to
filter out items from one set using a predicate capturing logic:
(set (filter #(contains? set2 %1) set1))
filter allows us to use a set in place of the first arg to filter, effectively treating it as a predicate to each item in the other set.
(set (filter set2 set1))
How simple? Code <=> Data for the win.