Clojure 递归与数据结构

发布于 2024-12-11 09:26:50 字数 226 浏览 0 评论 0原文

我已经尝试过此 Clojure 例程的多个版本,但它总是会导致空指针。我怎样才能消除这些错误?

(defn loopthru [n] (
  (if-not (empty? n) (
       (println (first n))
       (loopthru (rest n))
  ))
))
(loopthru [1 2 3 4 5 6])

谢谢,格雷格

I've tried several versions of this Clojure routine but it always results in a null pointer. How can I eliminate the errors?

(defn loopthru [n] (
  (if-not (empty? n) (
       (println (first n))
       (loopthru (rest n))
  ))
))
(loopthru [1 2 3 4 5 6])

Thanks, Greg

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

枫林﹌晚霞¤ 2024-12-18 09:26:50

正如每个人都指出的那样,您的 if-not 宏周围有双括号,这是不正确的。 (与Scheme不同,双括号在Clojure中很少是正确的。)但是你的if特殊形式还存在另一个问题。应该有一个 do 特殊形式来按顺序计算 s 表达式。

(defn loopthru [n]
  (if-not (empty? n)
    (do (println (first n))
     (loopthru (rest n)))))

还有其他一些事情。如果 if 语句中没有 else 块,请使用 when / when-not。事实上,在这种情况下使用 when-not 消除了对 do 的需要,因为 s 表达式中的条件没有歧义。我必须提到的强制性注释是,在这种情况下递归会占用堆栈空间,因此请使用 recur 代替

(defn loopthru [n]
  (when-not (empty? n)
    (println (first n))
    (recur (rest n))))

As everyone pointed out, you have double parentheses around your if-not macro which is not correct. (Double parentheses are rarely correct in Clojure, unlike Scheme.) But there is also another problem in your if special form. There should be a do special form which evaluates the s-expressions in order.

(defn loopthru [n]
  (if-not (empty? n)
    (do (println (first n))
     (loopthru (rest n)))))

A couple of other things. Use when / when-not in cases where you do not have an else block in your if statement. In fact, using when-not in this case eliminates the need for do since there is no ambiguity in the s-expressions with respect to the conditional. And I have to mention the obligatory comment that recursion in this case will chew up stack space so use recur instead

(defn loopthru [n]
  (when-not (empty? n)
    (println (first n))
    (recur (rest n))))
过期情话 2024-12-18 09:26:50
(defn loopthru [col]
  (doseq [n col] (println n)))

(defn loopthru [f col]
  (doseq [item col] (f item)))
(defn loopthru [col]
  (doseq [n col] (println n)))

(defn loopthru [f col]
  (doseq [item col] (f item)))
南风几经秋 2024-12-18 09:26:50

应省略函数体周围的一对括号。然后它就会起作用。

The pair of parentheses around the body of the function should be omitted. Then it will work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文