Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added takewhile #54

Merged
merged 10 commits into from
Dec 19, 2018
8 changes: 8 additions & 0 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,14 @@ Equivalent to `take`, but will throw an exception if fewer than `n` items are en
takestrict
```

## takewhile(cond, xs)

Iterates through values from the iterable `xs` as long as a given predicate `cond` is true.

```@docs
takewhile
```

## flagfirst(xs)

Provide a flag to check if this is the first element.
Expand Down
31 changes: 31 additions & 0 deletions src/IterTools.jl
Original file line number Diff line number Diff line change
Expand Up @@ -873,4 +873,35 @@ function iterate(ff::FlagFirst, state = (true, ))
(isfirst, elt), (isfirst & false, nextstate)
end

# TakeWhile iterates through values from an iterable as long as a given predicate is true.

struct TakeWhile{I}
cond::Function
xs::I
end

"""
takewhile(cond, xs)

An iterator that yields values from the iterator `xs` as long as the
predicate `cond` is true.

```jldoctest
julia> collect(takewhile(x-> x^2 < 10, 1:100)
3-element Array{Any,1}:
1
2
3
"""

ararslan marked this conversation as resolved.
Show resolved Hide resolved
takewhile(cond, xs) = TakeWhile(cond, xs)

function Base.iterate(it::TakeWhile, state=nothing)
(val, state) = state == nothing ? iterate(it.xs) : iterate(it.xs, state)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be state === nothing

it.cond(val) || return nothing
val, state
end

Base.IteratorSize(it::TakeWhile) = Base.SizeUnknown()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Define IteratorEltype and eltype as well, like I did in Ivec. Then you won't get Any arrays returned.


end # module IterTools
6 changes: 6 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -407,5 +407,11 @@ include("testing_macros.jl")

@test collect(flagfirst(Int[])) == Tuple{Bool,Int}[]
end

@testset "takewhile" begin
@test collect(takewhile(x -> x^2 < 10, 1:10)) == Any[1, 2, 3]
@test collect(takewhile(x -> x^2 < 10, Iterators.countfrom(1))) == Any[1, 2, 3]
@test collect(takewhile(x -> x^2 < 10, 5:10)) == Any[]
end
end
end