Skip to content

Instantly share code, notes, and snippets.

@madstap
Last active September 13, 2022 19:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madstap/7e769246583500312bb13d4b18db5d5e to your computer and use it in GitHub Desktop.
Save madstap/7e769246583500312bb13d4b18db5d5e to your computer and use it in GitHub Desktop.
car, cdr, cadadr and friends in clojure
(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