clojure:可以回退到第一个项目的下一个元素

leo*_*bot 0 clojure

我想创建一个getnext fn,它在coll中查找元素,当匹配时,返回下一个元素.此外,如果最后一个元素作为参数传递,它应该返回第一个元素.

(def coll ["a" "b" "c" "d"])

(defn get-next [coll item] ...)

(get-next coll "a") ;;=> "b"
(get-next coll "b") ;;=> "c"
(get-next coll "c") ;;=> "d"
(get-next coll "d") ;;=> "a" ; back to the beginning
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 7

这个怎么样:

  1. 在序列的末尾追加第一项(懒惰),

  2. 丢弃非物品,

  3. 返回剩下的内容(nil如果找不到项目).

或者在代码中:

    (defn get-next [coll item]
      (->> (concat coll [(first coll)])
           (drop-while (partial not= item))
           second))
Run Code Online (Sandbox Code Playgroud)