本文介绍了如何在Clojure中的if条件中调用recur?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试解决计数序列练习>。练习是计算集合中元素的数量,而不使用 count 函数。



我以为我可以通过递归,通过使用 rest 来执行此操作。如果我得到的不是空的,我返回 1 + recur在返回的序列rest 。问题是,我最终得到了

  java.security.PrivilegedActionException:java.lang.UnsupportedOperationException:
只是从尾位置复制

即使我调用 recur 作为最后一条语句。

 (fn [coll](let [tail(rest coll)] 
(if(empty tail)
1
(+ 1(recur tail)))))

解决方案

最后一个语句是加法,而不是调用 recur ,这是为什么它不工作。事实上,它在一个if与它无关。 (fn [coll](let [tail(rest coll)](+ 1(recur tail)))) b

将这样的函数转换为尾递归函数的常见方法是使函数接受第二个参数,它保存了您要添加的值的累加器,然后这样递归:(recur tail(+ acc 1))而不是尝试向 recur 的结果添加1。 p>

作为一般规则:如果你对 recur 的结果做任何事情(例如添加1 ),它不能在尾部位置,所以它不会工作。


I'm trying to solve the count a sequence excercise at 4clojure.com. The excercise is to count the number of elements in a collection without using the count function.

I thought I can do this via recursion, by the usage of rest. If what I get isn't empty, I return 1 + recur on the sequence rest returned. The problem is, that I end up getting

java.security.PrivilegedActionException: java.lang.UnsupportedOperationException:
Can only recur from tail position

even though I'm calling recur as the very last statement.

(fn [coll] (let [tail (rest coll)]
             (if (empty tail)
               1
               (+ 1 (recur tail)))))

Am I missing something?

解决方案

The last statement is the addition, not the call to recur, which is why it doesn't work. The fact that it's inside an if has nothing to do with it. (fn [coll] (let [tail (rest coll)] (+ 1 (recur tail)))) wouldn't work either.

The usual way to turn a function like this into a tail-recursive one is to make the function take a second argument, which holds the accumulator for the value you're adding up and then recurse like this: (recur tail (+ acc 1)) instead of trying to add 1 to the result of recur.

As a general rule: If you're doing anything to the result of recur (like for example adding 1 to it), it can't be in a tail position, so it won't work.

这篇关于如何在Clojure中的if条件中调用recur?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 20:22