Search code examples
clojure

What is the idiomatic way of returning the next member in collection?


What is the idiomatic way of returning the next item in collection, given a member in a collection?

For example, given (def coll [:a :b :c :d :e :f]), what should the f be to make (f coll :d) return :e?


Solution

  • As @amalloy said in his answer, this isn't something for which you would want to use the original data structure, because it would require a linear lookup every time. In other words, your (f coll :d) pattern wouldn't be a particularly useful thing due to its performance.

    However, what you could do is define a function that, given a collection, builds a data structure that makes this sort of lookup efficient, and use that as your function. It might look something like this:

    (defn after [xs]
      (into {} (map vec (partition 2 1 xs))))
    

    Examples:

    (-> [:a :b :c :d :e :f] after :d)
    ;;=> :e
    
    (let [xs [:a :b :c :d :e :f]
          f (after xs)]
      (map f xs))
    ;;=> (:b :c :d :e :f nil)