Search code examples
clojurefunctional-programming

get partial sequence clojure from a longer sequence


Given a sequence ("a","b","c","d","e"), what is the best way to get a subsequence of it, like ("c","d","e")?

I looked up subseq but it requires a test which in this case I want to be able to just supply the position.


Solution

  • The easiest way is to use drop & take:

    (def data  ["a","b","c","d","e"] )
    (take 3 (drop 2 data))
    

    If the data is a vector (square brackets, notice change above), you can use subvec:

    (subvec data 2 5)
    

    To ensure it is a vector, it is easy to use vec

    (subvec (vec data) 2 5)
    
    => ["c" "d" "e"]
    

    If you haven't seen them yet, you may want to checkout these resources:

    And, of course, The Clojure CheatSheet