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
35 changes: 34 additions & 1 deletion src/IterTools.jl
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export
peek,
ncycle,
ivec,
flagfirst
flagfirst,
takewhile

function has_length(it)
it_size = IteratorSize(it)
Expand Down Expand Up @@ -873,4 +874,36 @@ 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
"""
takewhile(cond, xs) = TakeWhile(cond, xs)

function Base.iterate(it::TakeWhile, state=nothing)
(val, state) = @ifsomething (state === nothing ? iterate(it.xs) : iterate(it.xs, state))
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.

eltype(::Type{TakeWhile{I}}) where {I} = eltype(I)
IteratorEltype(::Type{TakeWhile{I}}) where {I} = IteratorEltype(I)

end # module IterTools
7 changes: 7 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -407,5 +407,12 @@ 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[]
@test collect(takewhile(x -> true, 5:10)) == collect(5:10)
end
end
end