简体   繁体   English

循环先前定义的功能

[英]looping previously defined function

My goal is to iterate a function that I wrote, arbitrarily called gorilla, j times. 我的目标是将我编写的一个函数(任意称为gorilla)迭代j次。 Gorilla takes sequences as arguments. 大猩猩将序列作为参数。 However, the code is riddled with errors (not on purpose), and returns key must be an integer. 但是,代码充满错误(不是故意的),并且返回键必须是整数。

Here is a copy of the code: 这是代码的副本:

(defn gen-gorilla [seq j]
  (loop [level j gorilla seq]
    (if (= level 0)
      seq
      (if (> level 0)
        (recur (- level 1) (gorilla seq))))))  

This kind of thing is what iterate is most useful for. 这种事情是迭代最有用的。

(last (take 5 (iterate inc 0))) => 4 (last (take 5 (iterate inc 0))) => 4

so for this case you would want: 因此,在这种情况下,您需要:

(nth (iterate gorilla seq) j)

The problem in your code is that you are binding the name gorilla in your loop, but this means calling gorilla refers to the latest sequence, not the function. 代码中的问题是您在循环中绑定了名称gorilla ,但这意味着调用gorilla指的是最新序列,而不是函数。

This can actually be quite nicely written with reduce 这实际上可以用reduce很好地编写

 (defn apply-gorilla [n s]
    (reduce (fn [s _] (gorilla s)) s (range n)))

This basically loops up to n and ignores n as it goes, simply repeatedly applying gorilla repeatedly. 这基本上循环到n并忽略n ,简单地重复应用gorilla

If you really want explicit recursion 如果您真的想要显式递归

 (defn apply-gorilla [n s]
   (if (zero? n)
       s
       (recur (dec n) (gorilla s))))

The issue is in your use of gorilla in the recur call. 问题在于您在recur调用中使用gorilla gorilla in this case is a collection, defined in the loop statement, which, when you use them as functions is equivalent to indexing into them. 在这种情况下, gorilla是一个在loop语句中定义的集合,当您将它们用作函数时,它等效于对其进行索引。

([1 2 3] 0) ;; => 1

But, you are passing a sequence as the index into the collection. 但是,您正在将序列作为索引传递到集合中。

([1 2 3] [1 2 3]) ;; => Exception: Key must be integer

From your description, you are trying to call your function, gorilla , defined elsewhere. 根据您的描述,您正在尝试调用其他地方定义的函数gorilla You would need to rename the var defined in the loop statement to something like the following: 您需要将loop语句中定义的var重命名为以下内​​容:

(defn gen-gorilla [seq j]
  (loop [level j s seq]
    (if (= level 0)
      s
      (if (> level 0)
        (recur (- level 1) (gorilla s))))))

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

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