Clojure 递归与数据结构
我已经尝试过此 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如每个人都指出的那样,您的
if-not
宏周围有双括号,这是不正确的。 (与Scheme不同,双括号在Clojure中很少是正确的。)但是你的if特殊形式还存在另一个问题。应该有一个do
特殊形式来按顺序计算 s 表达式。还有其他一些事情。如果 if 语句中没有 else 块,请使用
when
/when-not
。事实上,在这种情况下使用when-not
消除了对do
的需要,因为 s 表达式中的条件没有歧义。我必须提到的强制性注释是,在这种情况下递归会占用堆栈空间,因此请使用recur
代替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 ado
special form which evaluates the s-expressions in order.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, usingwhen-not
in this case eliminates the need fordo
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 userecur
instead应省略函数体周围的一对括号。然后它就会起作用。
The pair of parentheses around the body of the function should be omitted. Then it will work.