how apply function on all element of array and get result as array in clojure? -
generally want know when have array of object have property can same "object literal in javascript" can calculated specific function. want create property array in clojure apply calculation on them such sorting or more simpler finding maximum according property.for example how try find maximum in example?
(def asqh (fn [x] (* x x))) (def masqh (max (apply asqh [1 2 3 4])))
the have error output object , not number
you seem thinking of mapping operation (take function of 1 argument , collection, replace every element result of function on element), in clojure called map
. apply
function plumbing collections functions if given each element separate argument. want use variadic functions (i.e. functions such max
, take variable number of arguments). instance
(def masqh (apply max (map asqh [1 2 3 4]))) ;;=> 16
if want preserve datatype of collection after performing mapping, can use into
, empty
:
(defn preserving-map [f coll] (into (empty coll) (map f coll))) (preserving-map asqh [1 2 3 4]) ;;=>[1 4 9 16] (preserving-map asqh #{1 2 3 4}) ;;=> #{1 4 9 16}
but removes (useful) laziness map
gives us. particular case of vectors (like [1 2 3 4]), use case common enough there mapv
eagerly performs mappings , puts them vector.
Comments
Post a Comment