【问题标题】:How to get tails of sequence clojure如何获得序列clojure的尾巴
【发布时间】:2014-10-08 21:00:38
【问题描述】:

我在它们的clojure中有序列

(1 2 3 4) 

我怎样才能得到像这样的序列的所有尾部

((1 2 3 4) (2 3 4) (3 4) (4) ())

【问题讨论】:

    标签: clojure functional-programming clojurescript


    【解决方案1】:

    另一种获得所有尾巴的方法是使用reductions 函数。

    user=> (def x '(1 2 3 4))
    #'user/x
    user=> (reductions (fn [s _] (rest s)) x x)
    ((1 2 3 4) (2 3 4) (3 4) (4) ())
    user=> 
    

    【讨论】:

      【解决方案2】:

      如果您想使用更高级别的函数来执行此操作,我认为iterate 在这里可以很好地工作:

      (defn tails [xs]
        (concat (take-while seq (iterate rest xs)) '(()))
      

      但是,我认为在这种情况下,使用lazy-seq 编写它会更简洁:

      (defn tails [xs]
        (if-not (seq xs) '(())
          (cons xs (lazy-seq (tails (rest xs))))))
      

      【讨论】:

      • 感谢这导致 ([1 2 3 4] (2 3 4) (3 4) (4) ()) 为什么第一个是矢量形式?
      • @hariszaman 这是因为 iterate 首先返回第二个参数本身而不应用该函数。然后它开始应用rest,它返回一个ChunkedSeq,它的打印方式与列表相同。
      【解决方案3】:

      这是一种方法。

      user=> (def x [1 2 3 4])
      #'user/x
      user=> (map #(drop % x) (range (inc (count x))))
      ((1 2 3 4) (2 3 4) (3 4) (4) ())
      

      【讨论】:

      • 这不应该用在惰性序列上,对 count 的调用会强制整个序列
      【解决方案4】:

      一种方法是通过

      (defn tails [coll]
        (take (inc (count coll)) (iterate rest coll)))
      

      【讨论】:

      • 这将强制任何惰性输入
      • 是的,由于计数。我真的没有考虑过。
      【解决方案5】:
      (defn tails
        [s]
        (cons s (if-some [r (next s)]
                  (lazy-seq (tails r))
                  '(()))))
      

      【讨论】:

      • 哦。呵呵。我猜我的 REPL 正在运行 1.5。
      • 你怎么能在 15 秒内回复?
      • 当您发表评论时,我正要关闭我的 SO 窗口。 :-)
      【解决方案6】:

      耶!另一个:

      (defn tails [coll]
          (if-let [s (seq coll)]
              (cons coll (lazy-seq (tails (rest coll))))
              '(())))
      

      这正是reductions 在幕后所做的。顺便说一句,最好的答案是ez121sl's

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多