递归地反转Clojure中的序列 [英] Recursively reverse a sequence in Clojure

查看:66
本文介绍了递归地反转Clojure中的序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Clojure中反转序列而不使用 reverse 函数,然后递归进行。

I want to reverse a sequence in Clojure without using the reverse function, and do so recursively.

这是我想出的:

(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])

问题:


  1. 有没有更简洁的方法,即没有循环/递归?

  2. 有没有一种方法可以在循环中不使用累加器参数呢?






参考文献:


References:

Whats the best way to recursively reverse a string in Java?

http://groups.google .com / group / clojure / browse_thread / thread / 4e7a4bfb0d71a508?pli = 1

推荐答案


  • 您不需要计数。在其余序列为空时停止。

  • 您不应该预先填充 acc ,因为原始输入可能为空(以及更多代码)。

  • 解构很酷。

    • You don't need to count. Just stop when the remaining sequence is empty.
    • You shouldn't pre-populate the acc, since the original input may be empty (and it's more code).
    • Destructuring is cool.
    • 
      (defn reverse-recursively [coll]
        (loop [[r & more :as all] (seq coll)
               acc '()]
          (if all
            (recur more (cons r acc))
            acc)))
      

      对于 loop / 递归 acc ,您需要一些方法来处理反向工作列表。它要么是 loop ,要么为函数添加了另一个参数(这实际上是 loop 所做的事情)。

      As for loop/recur and the acc, you need some way of passing around the working reversed list. It's either loop, or add another param to the function (which is really what loop is doing anyway).

      或使用高阶函数:

      
      user=> (reduce conj '() [1 2 3 4])
      (4 3 2 1)
      

      这篇关于递归地反转Clojure中的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆