Programming Languages

Simple Clojure Exercises

Note: This is a class activity, nothing needs to be delivered.

Create a Clojure source file called simple.clj. At the begining of the file add this code:

(use 'clojure.test)

and at the end add:

(run-tests)

All the code you write should go between these two instructions.

  1. Write a function called f2c that takes x degrees Fahrenheit and converts them to degrees Celsius. Unit tests:

    (deftest test-f2c
      (is (= 100.0 (f2c 212.0)))
      (is (= 0.0 (f2c 32.0)))
      (is (= -40.0 (f2c -40.0))))

    Tip: ºC = (ºF - 32) × 5 ÷ 9

  2. Write a function called sign that takes an integer value n. It returns -1 if n is negative, 1 if n is positive greater than zero, or 0 if n is zero. Unit tests:

    (deftest test-sign
      (is (= -1 (sign -5)))
      (is (= 1 (sign 10)))
      (is (= 0 (sign 0))))
    
  3. Write a function called roots that returns a vector containing the two possible roots that solve a quadratic equation given its three coefficients (a, b, c) using the following formula:

    Quadratic equation formula

    Unit tests:

    (deftest test-roots 
      (is (= [-1 -1] (roots 2 4 2)))
      (is (= [0 0] (roots 1 0 0)))
      (is (= [-1/4 -1] (roots 4 5 1))))
    

    Tip: To obtain the square root of a number, use the sqrt function defined in the clojure.math.numeric-tower namespace, like this:

    (use 'clojure.math.numeric-tower)
    
    (sqrt 25)
    => 5
    
  4. The BMI (body mass index) is used to determine if a person's weight and height proportion is adequate. The BMI may be calculated using the following formula:

    BMI = (weight) ÷ (height2)

    Where weight should be given in kilograms and height in meters. The following table shows how different BMI ranges are classified:

    BMI range Description
    BMI < 20 underweight
    20 ≤ BMI < 25 normal
    25 ≤ BMI < 30 obese1
    30 ≤ BMI < 40 obese2
    40 ≤ BMI obese3

    Write a function called bmi that takes two arguments: weight and height. It should return a symbol that represents the corresponding BMI description computed from its input.

    Unit tests:

    (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))))