简体   繁体   English

如何在数组的所有元素上应用函数并在clojure中将结果作为数组?

[英]how apply function on all element of array and get result as array in clojure?

generally i want to know when we have array of object that have some property can same the "Object Literal in JavaScript" can calculated with specific function. 通常我想知道我们何时具有某些属性的对象数组可以与“ JavaScript中的Object Literal”相同,并且可以使用特定函数进行计算。 i want to create that property for my array in clojure to apply some calculation on them such as sorting or more simpler finding maximum according to that property.for example how try find maximum in this example? 我想在clojure中为我的数组创建该属性以对其进行一些计算,例如排序或根据该属性更简单地找到最大值。例如在此示例中如何尝试找到最大值?

(def aSqh (fn [x] (* x x)))
(def maSqh (max (apply aSqh [1 2 3 4])))

the have error that output is object and not number 有错误,输出是对象而不是数字

You seem to be thinking of a mapping operation (take a function of one argument and a collection, replace every element with the result of the function on that element), which in Clojure is called map . 您似乎在考虑一种映射操作(采用一个参数和一个集合的函数,用该元素上函数的结果替换每个元素),在Clojure中将其称为map apply is a function for plumbing collections into functions as if they were given each element as a separate argument. apply是一个用于将集合收集到函数中的函数,就好像它们是作为每个元素的单独参数提供给它们一样。 Usually you want to use it with variadic functions (ie functions such as max , that take a variable number of arguments). 通常,您希望将其与可变参数函数一起使用(例如max ,这些函数带有可变数量的参数)。 For instance 例如

(def maSqh (apply max (map aSqh [1 2 3 4]))) ;;=> 16

If you want to preserve the datatype of a collection after performing a mapping, you can use into and empty : 如果要在执行映射后保留集合的数据类型,则可以使用intoempty

(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 this removes the (useful) laziness that map usually gives us. 但这消除了map通常给我们的(有用)懒惰。 For the particular case of vectors (like [1 2 3 4]), this use case is common enough that there is mapv which eagerly performs mappings and puts them into a vector. 对于矢量的特定情况(例如[1 2 3 4]),这种使用情况非常普遍,以至于有mapv急切地执行映射并将其放入矢量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM