Reputation: 1714
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?
Upvotes: 4
Views: 3794
Reputation: 6681
The other answer already gives you the right solution for finding the largest number. I would just like to add why your solution (which is returning something else anyway, not just the largest number, but also the list of all numbers previously considered as the largest) isn't working.
The problem is that in the argument list of your println
call, you are not calling top-one-list
, you are just referring to the function itself. You need to change that into (top-one-list boxes)
to call the function instead.
Upvotes: 0
Reputation: 96394
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)
Upvotes: 13