((a (b c d e)) (b (c-6ren">
gpt4 book ai didi

clojure - 有没有更简单的方法来获取序列的每个元素,并与 "its"尾部配对?

转载 作者:行者123 更新时间:2023-12-01 10:52:34 24 4
gpt4 key购买 nike

我发现自己需要将一个元素序列转换为“对”序列,其中第一个元素是初始序列的元素,而 while 的第二个元素是初始序列的尾部元素。

(a b c d e) -> ((a (b c d e)) (b (c d e)) (c (d e)) (d (e)) (e ()))

我是这样写的:

(defn head-and-tail [s]
(cond (empty? s) ()
:else (cons (list (first s) (rest s)) (head-and-tail (rest s)))))

是否有内置函数或内置函数的简单组合可以更轻松地执行此操作?

最佳答案

这是一种方法:

(let [xs [1 2 3 4]]
(map list xs (iterate rest (rest xs))))
;= ((1 (2 3 4)) (2 (3 4)) (3 (4)) (4 ()))

这当然可以根据您的需要进行调整,例如您可能更喜欢 map vector 而不是 map list 等。

此外,关于问题文本中的 head-and-tail impl:双向分支 cond 最好写成 if.

关于clojure - 有没有更简单的方法来获取序列的每个元素,并与 "its"尾部配对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17233497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com