Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: finding sequential items from a sequence

Tags:

clojure

reduce

In a Clojure program, I have a sequence of numbers:

(2 3 4 6 8 1)

I want to find the longest sub-sequence where the items are sequential:

(2 3 4)

I am assuming that it will involve (take-while ...) or (reduce ...).

Any ideas?

Clarification: I need the longest initial list of sequential items. Much easier, I'm sure. Thanks for the solutions to the more difficult problem I initially posed.

like image 964
Ralph Avatar asked Apr 27 '10 12:04

Ralph


1 Answers

If you are only interested in the longest initial sequence, it's a 1-liner:

(defn longest-initial-sequence [[x :as s]]
  (take-while identity (map #(#{%1} %2) s (iterate inc x))))
like image 191
cgrand Avatar answered Sep 25 '22 15:09

cgrand