尝试在 clojure 中对列表求幂时出现 #NaN 错误

Say*_*dal 0 clojure

我试图在 clojure 中对一个列表取幂。我编写了以下函数(基于建议):

(defn myfunc [x n] (map #(Math/exp % n) x)) 
Run Code Online (Sandbox Code Playgroud)

但是当输入 x = (list 'a 'b) 和 n = 2 时,(list 'a 'b 'a 'b)它不会抛出##NaN ##NaN

任何建议表示赞赏。我想我仍然缺少函数式编程语言中涉及的一些抽象。

Den*_*ida 5

我认为混淆是与术语exponentiation。您可以对数字取幂(将数字本身乘以给定的幂),因此我认为您已获得有关如何对给定列表的所有数字执行此操作的建议。

在 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)
Run Code Online (Sandbox Code Playgroud)

但是在您的示例中,列表是任意名称(而不是数字)的列表,我认为这个想法是您想要多次重复列表。我可以想到几个选项来实现它:

选项1

repeat 接受一个数字和一个元素,并创建一个重复 N 次的所述元素的序列:

user=> (repeat 2 [1 2 3])
([1 2 3] [1 2 3])
Run Code Online (Sandbox Code Playgroud)

现在我们需要concat生成结果:

user=> (apply concat (repeat 2 [1 2 3]))
(1 2 3 1 2 3)
Run Code Online (Sandbox Code Playgroud)

有了这个,我们可以定义以下函数:

(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)
Run Code Online (Sandbox Code Playgroud)

选项 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)
Run Code Online (Sandbox Code Playgroud)

您可以使用 获得序列的长度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)
Run Code Online (Sandbox Code Playgroud)