DEV Community


Discussion on: Which concept took you the longest to grasp?

jffrydsr profile image
Jeffrey Desir

Soon (enough 🙄) my affinity for LISPs & Clojure will be matched with my discursive posts. The most rewarding & self-damning attempt I'd ever made in my CS career is learning Clojure 🌟macros🌟.
random example:
often when we repeat declarative patterns (do this with this) we capture their behavior in functions or methods

(ns example.macros)

;; simple script to compare variable against 0. 
(defn heat 0.001)

(if (not (= 0.0 heat))
     (println "Cannot cohere!"))
Enter fullscreen mode Exit fullscreen mode

To capture the if atoms behavior, let's try a function first.

(defn if-cohereable [value dispatch]
  (if (not (= 0.0 value))
     (println "Cannot cohere!"

;; nice! but a few problems in practice...
(defn run-program [ :keys [ actions, H* ;;Heat Operator ]] 
   (if-cohereable H* (actions)))

(run-program :H* 0)

=> #<clojure.function>
Enter fullscreen mode Exit fullscreen mode

looks helpful, but we can't actually use this as an 'if' statement, just a comparator that returns a function.
With the power of Macro though

(defmacro if-cohereable [ :keys [H* actions-body ]]
   (if (not (= 0 H*))
      ;;throw error if comparison fails
     (throw "Non-zero-energy prevents entanglment!")
     ;;otherwise run the body of code passed into macro call

;; now in action...

(defn run-program [ energy ]
  (if-cohereable :H* energy ;;named arities with if-statement
      (init! energy)
Enter fullscreen mode Exit fullscreen mode

😅 a rather innocuous example but point is I couldn't grasp the use-cases for this meta-programming feature until I labored through documents & examples & uses before I understood the sheer power in talking about code the same as data.

The closest thing I know to LISPs macro power are most other languages Proxy Generator or Iterator capabilities and although they mirror much of LISPs flexibility, they are SYNTACTICALLY inefficient to express data transformations (all code is) fully.
✌🏿 It was a pain and a pleasure both learning and sharing ~