|
| 1 | +struct EnumerableExcept{T,TKEY,S1,S2,Q<:Function} <: Enumerable |
| 2 | + first::S1 |
| 3 | + second::S2 |
| 4 | + f::Q |
| 5 | +end |
| 6 | + |
| 7 | +Base.eltype(::Type{EnumerableExcept{T,TKEY,S1,S2,Q}}) where {T,TKEY,S1,S2,Q} = T |
| 8 | + |
| 9 | +function except(first::Enumerable, second::Enumerable) |
| 10 | + T1 = eltype(first) |
| 11 | + T2 = eltype(second) |
| 12 | + |
| 13 | + _check_same_eltype("except", T1, T2) |
| 14 | + |
| 15 | + return EnumerableExcept{T1,T1,typeof(first),typeof(second),typeof(identity)}(first, second, identity) |
| 16 | +end |
| 17 | + |
| 18 | +# Unlike Enumerable.ExceptBy, whose second argument is a sequence of keys, the |
| 19 | +# key selector here is applied to both sequences. That keeps `except_by` |
| 20 | +# consistent with `union_by`, matches the shape of the equivalent SQL |
| 21 | +# (`WHERE k NOT IN (SELECT k FROM b)`), and is what a table-shaped second |
| 22 | +# argument makes natural. |
| 23 | +function except_by(first::Enumerable, second::Enumerable, f::Function, f_expr::Expr) |
| 24 | + T1 = eltype(first) |
| 25 | + T2 = eltype(second) |
| 26 | + |
| 27 | + TKEY1 = Base._return_type(f, Tuple{T1,}) |
| 28 | + TKEY2 = Base._return_type(f, Tuple{T2,}) |
| 29 | + |
| 30 | + _check_same_keytype("except_by", TKEY1, TKEY2) |
| 31 | + |
| 32 | + return EnumerableExcept{T1,TKEY1,typeof(first),typeof(second),typeof(f)}(first, second, f) |
| 33 | +end |
| 34 | + |
| 35 | +function Base.iterate(iter::EnumerableExcept{T,TKEY,S1,S2,Q}) where {T,TKEY,S1,S2,Q} |
| 36 | + excluded = Set{TKEY}() |
| 37 | + for i in iter.second |
| 38 | + push!(excluded, iter.f(i)) |
| 39 | + end |
| 40 | + |
| 41 | + return _except_next(iter, excluded, Set{TKEY}(), _NotStarted()) |
| 42 | +end |
| 43 | + |
| 44 | +function Base.iterate(iter::EnumerableExcept, state) |
| 45 | + return _except_next(iter, state.excluded, state.observed, state.state) |
| 46 | +end |
| 47 | + |
| 48 | +# Yields the distinct elements of the first source whose key does not occur in |
| 49 | +# the second, matching Enumerable.Except's de-duplicating behaviour. |
| 50 | +function _except_next(iter::EnumerableExcept, excluded, observed, source_state) |
| 51 | + while true |
| 52 | + ret = _iterate_from(iter.first, source_state) |
| 53 | + ret === nothing && return nothing |
| 54 | + |
| 55 | + element, source_state = ret |
| 56 | + k = iter.f(element) |
| 57 | + if !(k in excluded) && !(k in observed) |
| 58 | + push!(observed, k) |
| 59 | + return element, (excluded=excluded, observed=observed, state=source_state) |
| 60 | + end |
| 61 | + end |
| 62 | +end |
0 commit comments