Search code examples
clojurefunctional-programming

Display parallel Clojure array and range values


The following function takes a range of Celcius temperatures, converts them to Fahrenheit, and puts them into an array.

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

My goal is then to print each converted temperature in the following format:

C[0] = 32 F
C[1] = 33.8 F
...

The format doesn't really matter. I'm new to functional programming and still thinking the OOP

way. I tried to use the map function to do that. What should I go with? Map, reduce, for, doall?

So far I came up with the following:

  1. display-format function should display something like this C[0] =. I'm not sure how to place that [index] there though.

    (defn display-format [t-scale] (println t-scale "=" ))

  2. display-array function should use the map function to apply display-format function to the array.

    (defn display-array [t-scale array] (map (display-format t-scale) array))

Am I going in the right direction?

Update: Here the code I was going for. Hope it helps someone.

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

Solution

  • Please see this list of documentation. Especially study the Clojure CheatSheet.

    For your purposes, study

    1. doseq for looping over the values to print output
    2. format for using %d and similar output formatting options
    3. str for concatenating strings
    4. I'd suggest making a function celcius->farenheit and then calling that in a loop. Call double on the input arg and it will avoid any worries about int vs float all the way downstream.
    5. I always prefer mapv over map to eliminate problems from laziness

    Enjoy!