我想在 Clojure 中反转序列而不使用reverse
函数,并递归地执行此操作。
这是我想出的:
(defn reverse-recursively [coll]
(loop [r (rest coll)
acc (conj () (first coll))]
(if (= (count r) 0)
acc
(recur (rest r) (conj acc (first r))))))
示例输出:
user> (reverse-recursively '(1 2 3 4 5 6))
(6 5 4 3 2 1)
user> (reverse-recursively [1 2 3 4 5 6])
(6 5 4 3 2 1)
user> (reverse-recursively {:a 1 :b 2 :c 3})
([:c 3] [:b 2] [:a 1])
问题:
- 有没有更简洁的方法来做到这一点,即没有循环/重复?
- 有没有办法在循环中不使用“累加器”参数来做到这一点?
参考:
在Java中递归反转字符串的最佳方法是什么? https://stackoverflow.com/questions/859562/whats-the-best-way-to-recursively-reverse-a-string-in-java
http://groups.google.com/group/clojure/browse_thread/thread/4e7a4bfb0d71a508?pli=1 http://groups.google.com/group/clojure/browse_thread/thread/4e7a4bfb0d71a508?pli=1
- 你不需要数。当剩余序列为空时停止。
- 您不应该预先填充
acc
,因为原始输入可能是空的(而且是更多代码)。
- 解构很酷。
(defn reverse-recursively [coll]
(loop [[r & more :as all] (seq coll)
acc '()]
(if all
(recur more (cons r acc))
acc)))
As for loop
/recur
和acc
,您需要某种方式来传递工作反转列表。要么是loop
,或者向函数添加另一个参数(这实际上是loop
无论如何都在做)。
或者使用高阶函数:
user=> (reduce conj '() [1 2 3 4])
(4 3 2 1)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)