Last active
September 13, 2022 19:15
-
-
Save madstap/7e769246583500312bb13d4b18db5d5e to your computer and use it in GitHub Desktop.
car, cdr, cadadr and friends in clojure
This file contains 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
(ns car | |
"The sixties are back!" | |
(:require | |
[clojure.math.combinatorics :as combo])) | |
(defn ad-combos [n] | |
(distinct | |
(mapcat (fn [i] | |
(combo/selections '[a d] i)) | |
(range 1 (inc n))))) | |
(defn make-name [combo] | |
(symbol (str "c" (apply str combo) "r"))) | |
(def ad->fn | |
{'a `first, 'd `next}) | |
(defn make-fn [combo] | |
`(comp ~@(map ad->fn combo))) | |
(defmacro defcadrs | |
([] `(defcadrs 4)) | |
([n] | |
(vec (for [combo (ad-combos n)] | |
`(defn ~(make-name combo) | |
[~'coll] | |
(~(make-fn combo) ~'coll)))))) | |
(defcadrs 6) | |
(comment | |
;; Yay, super readable code! | |
;; Can you guess what each one evaluates to? | |
(caddar '((peas carrots tomatoes) (pork beef chicken) duck)) | |
(cadadr '((peas carrots tomatoes) (pork beef chicken) duck)) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment