Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the largest number from a list in clojure

Tags:

clojure

I am very very verrrrryyy new (as in started yesterday) to Clojure.

I have a list of numbers and need to find the largest one in the list.

I have come up with something like this so far:

  def boxes [1 2 3 4 5])

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

That last println gives me some weird thing:

  #<core$_main$top_one_list__30 proj_one.core$_main$top_one_list__30@13c0b53>

Any ideas?

like image 422
lulu88 Avatar asked Dec 11 '22 11:12

lulu88


1 Answers

The function max returns the maximum of the arguments it's passed:

(max 1 2 3 4 5)

To call it with a sequence you can use apply:

(apply max boxes)

Dao Wen makes a good point that if the sequence may be empty then reduce allows specifying a default value:

(reduce max -1 [])  # returns -1

and the same works for apply:

(apply max -1 []) # returns -1 

Otherwise apply will blow up:

user=> (apply max [])
ArityException Wrong number of args (0) passed to: core$max  clojure.lang.AFn.th
rowArity (AFn.java:437)
like image 126
Nathan Hughes Avatar answered Dec 28 '22 23:12

Nathan Hughes