;----------------------------------------------------------- ; Solutions to the simple Clojure exercises. ;----------------------------------------------------------- (ns simple (:use clojure.test)) (defn f2c [x] (/ (* (- x 32.0) 5.0) 9)) (defn sign [n] (if (> n 0) 1 (if (< n 0) -1 0))) (defn roots [a b c] (let [d (- b) e (Math/sqrt (- (* b b) (* 4 a c))) f (* 2 a)] [(/ (+ d e) f) (/ (- d e) f)])) ;;; First version: using nested if's. ; (defn bmi [weight height] ; (let [BMI (/ weight (* height height))] ; (if (< BMI 20) ; 'underweight ; (if (< BMI 25) ; 'normal ; (if (< BMI 30) ; 'obese1 ; (if (< BMI 40) ; 'obese2 ; 'obese3)))))) ;;; Second version: using cond. (defn bmi [weight height] (let [BMI (/ weight (* height height))] (cond (< BMI 20) 'underweight (< BMI 25) 'normal (< BMI 30) 'obese1 (< BMI 40) 'obese2 :else 'obese3))) (deftest test-f2c (is (= 100.0 (f2c 212.0))) (is (= 0.0 (f2c 32.0))) (is (= -40.0 (f2c -40.0)))) (deftest test-sign (is (= -1 (sign -5))) (is (= 1 (sign 10))) (is (= 0 (sign 0)))) (deftest test-roots (is (= [-1.0 -1.0] (roots 2.0 4.0 2.0))) (is (= [0.0 0.0] (roots 1.0 0.0 0.0))) (is (= [-0.25 -1.0] (roots 4.0 5.0 1.0)))) (deftest test-bmi (is (= 'underweight (bmi 45 1.7))) (is (= 'normal (bmi 55 1.5))) (is (= 'obese1 (bmi 76 1.7))) (is (= 'obese2 (bmi 81 1.6))) (is (= 'obese3 (bmi 120 1.6)))) (run-tests)