gpt4 book ai didi

clojure - 如何多次将函数应用于序列

转载 作者:行者123 更新时间:2023-12-02 22:27:27 25 4
gpt4 key购买 nike

我正在研究一些 Lisp exercises使用 Clojure。我尝试在不利用向量和一些 Clojure 函数的情况下完成这些练习。

这个函数

(defn rev-seq
[s1]
(concat (pop s1) (list (peek s1))))

将列表的第一个元素放在末尾。我想多次调用此函数来反转列表(不调用 Clojure 的 reverse 函数)。

我不确定用什么代替它。我已经尝试过映射、应用和重复,但没有成功。我宁愿有一种不同的方式来思考这个问题,而不是一个直接的答案,但我不要求进行讨论。

最佳答案

首先,我认为您需要将 rev-seq 转换为使用 first/rest 而不是 peek/pop 如果您想处理一般序列 - 至少在 Clojure 1.4 中 peek/pop 似乎需要一个 PersistentStack:

(defn rev-seq
[s1]
(concat (rest s1) (list (first s1))))

然后您可能应该注意到重复应用此函数将“循环”列表而不是反转它。您可以看到,如果您使用 iterate 查看少量应用程序的结果:

(def s '(1 2 3 4 5 6 7 8 9))

(nth (iterate rev-seq s) 3)
=> (4 5 6 7 8 9 1 2 3)

一个可行的选项是使用递归函数反转:

(defn reverse-seq [s]
(concat (reverse (next s)) (list (first s))))

(reverse-seq s)
=> (9 8 7 6 5 4 3 2 1)

或者您可以使用 clojure.core 中的技术进行反向操作:

(defn reverse-seq [s]
(reduce conj () s))

(reverse-seq s)
=> (9 8 7 6 5 4 3 2 1)

希望这能给你一些想法!

关于clojure - 如何多次将函数应用于序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12754981/

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