Using Clojure's filter to find entry with minimum value -
i developed function using clojure returns row minimum value determined. here function that:
(#(reduce (fn [r1 r2] (let [v1 (read-string (apply str (clojure.string/split (get r1 %2) (re-pattern " ")))) v2 (read-string (apply str (clojure.string/split (get r2 %2) (re-pattern " "))))] (if (< v1 v2) r1 r2))) %1) [[1 "2007 05 18"] [2 "2004 06 15"] [3 "2004 06 10"]] 1)
returns:
[3 "2004 06 10"]
question want implement above function predicate filter function return same result above function. please how do this? thanks
given reasonable assumption have dates, , want row lower date.
this approach using sort-by
.
(sort-by (fn [[idx date]] (let [[_ y m d] (re-find #"\d{4} \d{2} \d{2}" date)] y)) [[1 "2007 05 18"] [2 "2004 06 15"] [3 "2004 06 10"]])
or can parse input string date , avoid regex
added benefit of sorting year, month , day.
(sort-by (fn [[idx date]] (.parse (java.text.simpledateformat. "yyyy mm dd") date)) [[1 "2007 05 18"] [2 "2004 06 15"] [3 "2004 06 10"]]) => ([3 "2004 06 10"] [2 "2004 06 15"] [1 "2007 05 18"])
then take first
or last
of result lowest or highest valued row.
using filter
makes no sense, since filter
doesn't accumulate state, need in order compare rows among each other. (that's you're doing manually reduce
function).
filtering sequence predicate give rows matching predicate, nothing relationship between rows themselves.
that's why sort-by
idiomatic way sort custom function in situation.
even better, if assume lexicographic sort of stringified date matches order want, can do:
(sort-by second [[1 "2007 05 18"] [2 "2004 06 15"] [3 "2004 06 10"]]) => ([3 "2004 06 10"] [2 "2004 06 15"] [1 "2007 05 18"])
Comments
Post a Comment