clojure: Next element of an item that can fallback to first

  • A+
Category:Languages

I'd like to create a getnext fn that looks for a element in a coll and when match, return the next element. Also, it should return the first element if the last one is passed as argument.

(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 

Thanks!


How about this:

  1. Append first item at the end of the sequence (lazily),

  2. Drop non-items,

  3. Return what's left (nil if item not found).

Or in code:

    (defn get-next [coll item]       (->> (concat coll [(first coll)])            (drop-while (partial not= item))            second)) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: