2

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.

3 Answers 3

6

You probably want to use take-while:

(take-while #(> % 0) '(1 2 3 0 3 2 0 1))
=> (1 2 3)
Sign up to request clarification or add additional context in comments.

1 Comment

Or even (take-while pos? '(1 2 3 0 3 2 0 1)), in this specific case.
3

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)]

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.