Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created November 23, 2020 15:27
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 ericnormand/2318405631f158d6f2ceaaff3161c6c4 to your computer and use it in GitHub Desktop.
Save ericnormand/2318405631f158d6f2ceaaff3161c6c4 to your computer and use it in GitHub Desktop.
404 - PurelyFunctional.tv Newsletter

Boolean combinators

In the Clojure Tip above, I described a kind of Boolean combinator that lets us build complex rules out of simpler rules. Your task is to build those combinators. Please define:

(defn rule-and
  ([])
  ([rule])
  ([rule1 rule2])
  ([rule1 rule2 & rules]))
(defn rule-or
  ([])
  ([rule])
  ([rule1 rule2])
  ([rule1 rule2 & rules]))
(defn rule-not [rule])

Note that rule-and and rule-or are monoids and so they follow the monoid pattern.

For a bonus, write the functions rule-if (that implements the logical if arrow operator) and rule-iff (that implements the logical if and only if double-arrow operator). Not that rule-if is different from the programming if since it returns true if the condition is false.

Please submit your solutions as comments on this gist.

@KingCode
Copy link

KingCode commented Nov 26, 2020

This is just a thought, but while "testing" rule-if/iff, I remembered that these are tautologies, i.e. that timeless properties such as (rule-iff even? (complement odd?)) and (rule-if #(= 0 (rem % 4)) even?) are always true.

In the limited experience I had with spec and test.check, I have always struggled to identify (timeless) properties: rule-if would probably be a great way to test-discover properties using test.check generators.

Has anyone here tried this before?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment