kakarukeys
kakarukeys

Reputation: 23411

Clojure sequence operation

How to get a new sequence from an old sequence, the elements of the new one are from the old one until a condition is met

Suppose the condition is #(> % 0)

'(1 2 3 0 3 2 0 1) returns 1, 2, 3

'(0 1 2 3) returns empty seq

'(1 2 3) returns everything.

Note it's not same as filter.

Upvotes: 2

Views: 143

Answers (3)

jbear
jbear

Reputation: 363

This is the joy of Clojure: there are so many ways to skin a cat:

(for [i '(1 2 3 0 3 2 0 1) :while (> i 0)] i)
=> (1 2 3)

Upvotes: 2

sw1nn
sw1nn

Reputation: 7328

mikera's answer looks good, but also consider split-with if you need to do further processing on the rest of the list.

=> (split-with #(> % 0) '(1 2 3 0 3 2 0 1))
[(1 2 3) (0 3 2 0 1)]

Upvotes: 3

mikera
mikera

Reputation: 106351

You probably want to use take-while:

(take-while #(> % 0) '(1 2 3 0 3 2 0 1))
=> (1 2 3)

Upvotes: 6

Related Questions