Programming Fundamentals/Arrays/Clojure

From Wikiversity
Jump to navigation Jump to search

arrays.clj[edit | edit source]

;; This program uses arrays to display temperature conversion tables 
;; and temperature as an array subscript to find a given conversion.
;;
;; Reference:
;;     https://www.mathsisfun.com/temperature-conversion.html

(defn build-f [size]
    (mapv float (map #(+(/(* % 9)5)32) (range (+ size 1)))))

(defn build-c [size]
    (mapv float (map #(/(*(- % 32)5)9) (range (+ size 1)))))

(defn display-table [from-scale array to-scale]
  (map #(println (str from-scale "[" %1 "] = " %2 " " to-scale))
                 (range (count array)) array))

(defn minimum [value1, value2]
  (if (< value1 value2) value1 value2))

(defn find-temperature [c f]
  (let [size (minimum (count c) (count f))
        _ (println (str "\nEnter a temperature between 0 and " (- size 1) ":"))
        temperature (Float/parseFloat (read-line))]
    (println (str "\n" temperature "° Fahrenheit is " (nth c temperature) "° Celsius."))
    (println (str temperature "° Celsius is " (nth f temperature) "° Fahrenheit."))))

(defn -main []
    (let [f (build-f 100)
          c (build-c 212)]
         (dorun (display-table "C" f "F"))
         (dorun (display-table "F" c "C"))
         (dorun (find-temperature c f))))

(-main)

Try It[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Clojure compiler / interpreter / IDE.

See Also[edit | edit source]