我正在完成第7个练习,位于https://iloveponies.github.io/120-hour-epic-sax-marathon/one-function-to-rule-them-all.html。我有一个解决方案,但由于期望的输出是列表,所以我不得不在一些输出中添加“reverse”。这似乎有点繁琐。
以下是我的代码:
(defn insert [sorted-seq n]
(loop [output ()
my-seq sorted-seq]
(cond
(nil? (first my-seq))
(conj output n)
(nil? (first (rest my-seq)))
(reverse (conj output (first my-seq) n))
:else
(if (> (first (rest my-seq)) n (first my-seq))
(reverse (apply conj output (first my-seq) n (rest my-seq)))
(recur (conj output (first my-seq)) (rest my-seq))))))
(insert [] 2) ;=> (2)
(insert [1 3 4] 2) ;=> (1 2 3 4)
(insert [1] 2) ;=> (1 2)
有没有更好的方法编写这个代码以提高效率,而不需要反转输出?此外,前两个条件似乎很笨拙。是否有更好的方法呢?