DEV Community

Cover image for Programming in Clojure (Part 6 Macros)
Mark Mahoney
Mark Mahoney

Posted on • Updated on

Programming in Clojure (Part 6 Macros)

This post covers macros in Clojure. A macro specifies some code to be executed sort of like a function but it also allows some of that code to be replaced with values that come from the user. The code in a macro is kind of like a template that can be altered to suit the callers needs. With this powerful feature the language can be expanded to do things that the language inventor never thought to add.


Call to Action

Problem 1
Write a macro that takes in a grade earned on a student assignment (on a 0-100 scale) and some code to execute if the grade is a passing or failing.

(defmacro eval-grade [grade if-passing if-failing] ...)
Enter fullscreen mode Exit fullscreen mode

And use it to print or call a function based on the value of the grade

(def users-grade 43)
(eval-grade users-grade (println "Passing") (println "Failing")) ;;"Failing"
(eval-grade users-grade (praise users-grade) (warning users-grade)) ;;call the warning function
Enter fullscreen mode Exit fullscreen mode

Comments and Feedback

You can find all of these code playbacks in my free 'book', An Animated Introduction to Clojure. I am always looking for feedback so please feel free to comment here or to send me a message. You can follow me on twitter @markm208.

Top comments (0)