Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: max of list

Tags:

clojure

Try to write Clojure program: Define the function maxim to find the largest element in the list

(def boxes [33 11 44 22 66 55])

(println "List of box volumes:" boxes)

(defn top-one [[big1 :as acc] x]
  (cond
    (> x big1) [x big1]
    :else acc))

(defn top-one-list [boxes]
  (reduce top-one [0] boxes))

(println "Biggest volume from boxes:" top-one-list)
    (println "Biggest volume from boxes:" top-one-list)

But the output result is:66 44, it print two numbers,who could help me

like image 354
bin Avatar asked Oct 18 '25 12:10

bin


1 Answers

This line:

(> x big1) [x big1]

Returns two elements. You only want one.

It should be:

(> x big1) [x]

A cleaner way to write it would be not to use a list, but only a number as the state of the reduction process:

(defn top-one [big1 x]
  (if (> x big1)
    x
    big1))

(defn top-one-list [boxes]
  (reduce top-one 0 boxes))
like image 122
Reut Sharabani Avatar answered Oct 21 '25 12:10

Reut Sharabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!