HomeMathEmailBlogGitHub

Pre and Post in Clojure

2023-06-15

Pre-conditions are boolean expressions that must evaluate to true before a function is evaluated and post-conditions are the same thing but for after a function's evaluation. If a pre or post condition is violated, an error will be thrown. Adding pre and post conditions to a function can allow programmers to ensure dynamic type safety. A pre-condition in Clojure looks like this:

(defn factorial [n]
  {:pre [(>= n 0)]}
  (if (= n 0)
    1
    (* n (factorial (dec n)))))

Here, the precondition is that n is greater than or equal to 0, so if I do (factorial -1) the following error is thrown:

AssertionError Assert failed: (>= n 0)

This style of programming is called Design by Contract, though usually Test Driven Development is used over Design by Contract to ensure dynamic type safety.