尝试对 clojure 中的列表求幂时出现 #NaN 错误
#NaN error while trying to exponentiate a list in clojure
我正在尝试对 clojure 中的列表取幂。我写了以下函数(根据建议):
(defn myfunc [x n] (map #(Math/exp % n) x))
但是当输入 x = (list 'a 'b) 和 n = 2 时,它抛出 ##NaN ##NaN
而不是 (list 'a 'b 'a 'b)
如有任何建议,我们将不胜感激。我想我仍然缺少函数式编程语言中涉及的一些抽象。
我认为混淆与术语 求幂有关。您可以对数字取幂(将数字本身乘以给定的幂),因此我认为您已获得有关如何对给定列表的所有 数字 执行此操作的建议。
在 Clojure 中,以下内容如您所愿:
user=> (defn myfunc [x n] (map #(Math/pow % n) x))
#'user/myfunc
user=> (myfunc [1 2 3] 2)
(1.0 4.0 9.0)
但在您的示例中,该列表是任意名称(不是数字)的列表,我认为您想要重复一个列表多次。我可以想到几个实现它的选项:
选项 1
repeat
获取一个数字和一个元素,并创建一个重复 N 次的所述元素的序列:
user=> (repeat 2 [1 2 3])
([1 2 3] [1 2 3])
现在我们需要concat
生成结果:
user=> (apply concat (repeat 2 [1 2 3]))
(1 2 3 1 2 3)
据此,我们可以定义以下函数:
(defn repeat-list [lst n]
(apply concat (repeat n lst)))
(repeat-list (list 'a 'b 'c) 3)
;; => (a b c a b c a b c)
选项 2
您可以创建一个 无限 给定序列的元素序列 cycle
:
;; We use 'take' here to get a *finite* number of elements:
user=> (take 10 (cycle [1 2 3]))
(1 2 3 1 2 3 1 2 3 1)
你可以用count
得到一个序列的长度。对于大小为 N 且重复 2 次的列表,您需要 2 * N 个元素,如下所示:
(defn repeat-list [lst n]
(take (* n (count lst)) (cycle lst)))
(repeat-list (list 'a 'b 'c) 3)
;; => (a b c a b c a b c)
我正在尝试对 clojure 中的列表取幂。我写了以下函数(根据建议):
(defn myfunc [x n] (map #(Math/exp % n) x))
但是当输入 x = (list 'a 'b) 和 n = 2 时,它抛出 ##NaN ##NaN
(list 'a 'b 'a 'b)
如有任何建议,我们将不胜感激。我想我仍然缺少函数式编程语言中涉及的一些抽象。
我认为混淆与术语 求幂有关。您可以对数字取幂(将数字本身乘以给定的幂),因此我认为您已获得有关如何对给定列表的所有 数字 执行此操作的建议。
在 Clojure 中,以下内容如您所愿:
user=> (defn myfunc [x n] (map #(Math/pow % n) x))
#'user/myfunc
user=> (myfunc [1 2 3] 2)
(1.0 4.0 9.0)
但在您的示例中,该列表是任意名称(不是数字)的列表,我认为您想要重复一个列表多次。我可以想到几个实现它的选项:
选项 1
repeat
获取一个数字和一个元素,并创建一个重复 N 次的所述元素的序列:
user=> (repeat 2 [1 2 3])
([1 2 3] [1 2 3])
现在我们需要concat
生成结果:
user=> (apply concat (repeat 2 [1 2 3]))
(1 2 3 1 2 3)
据此,我们可以定义以下函数:
(defn repeat-list [lst n]
(apply concat (repeat n lst)))
(repeat-list (list 'a 'b 'c) 3)
;; => (a b c a b c a b c)
选项 2
您可以创建一个 无限 给定序列的元素序列 cycle
:
;; We use 'take' here to get a *finite* number of elements:
user=> (take 10 (cycle [1 2 3]))
(1 2 3 1 2 3 1 2 3 1)
你可以用count
得到一个序列的长度。对于大小为 N 且重复 2 次的列表,您需要 2 * N 个元素,如下所示:
(defn repeat-list [lst n]
(take (* n (count lst)) (cycle lst)))
(repeat-list (list 'a 'b 'c) 3)
;; => (a b c a b c a b c)