How to get the largest number from a list in clojure

I am very very verrrrryyy new (like at the beginning yesterday) before Clojure.

I have a list of numbers and you need to find the largest of them.

I came up with something like this:

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) 

This last println gives me some weird thing:

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

Any ideas?

+4
source share
2 answers

The max function returns the maximum of the arguments that it passed:

 (max 1 2 3 4 5) 

To call it using a sequence that you can use, follow these steps:

 (apply max boxes) 

Dao Wen is well aware that if the sequence can be empty, then the abbreviation allows you to specify the default value:

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

and the same work for application:

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

Otherwise, the application will explode:

 user=> (apply max []) ArityException Wrong number of args (0) passed to: core$max clojure.lang.AFn.th rowArity (AFn.java:437) 
+12
source

Another answer already gives you the right solution to find the largest number. I just wanted to add why your solution (which in any case returns something else, and not just the largest number, as well as a list of all numbers that were previously considered the largest) does not work.

The problem is that in the argument list of your println call you are not calling top-one-list , you are simply accessing the function itself. You need to change this to (top-one-list boxes) to call the function.

0
source

Source: https://habr.com/ru/post/1502432/


All Articles