September 29, 2018

Just Juxt #46: Comparisons (4clojure #166)


For any orderable data type it's possible to derive all of the basic comparison operations (<_ _="_" and="and">) from a single operation (any operator but = or ≠ will work). Write a function that takes three arguments, a less than operator for the data and two items to compare. The function should return a keyword describing the relationship between the two items. The keywords for the relationship between x and y are as follows:

  • x = y → :eq
  • x > y → :gt
  • x < y → :lt
(ns live.test
  (:require [cljs.test :refer-macros [deftest is run-tests]]))

(defn comparisons [a b c]
  (case (map (juxt a (complement a)) [b c] [c b])
    [[true false] [false true]] :lt
    [[false true] [false true]] :eq
    [[false true] [true false]] :gt))

(deftest comparisons-test
  (is (= :gt (comparisons < 5 1)))
  (is (= :eq (comparisons (fn [x y] (< (count x) (count y))) "pear" "plum")))
  (is (= :lt (comparisons (fn [x y] (< (mod x 5) (mod y 5))) 21 3)))
  (is (= :gt (comparisons > 0 2))))
Tags: coding exercises KLIPSE 4clojure Cryogen juxt