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

Add filter_terms #287

Merged
merged 2 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/src/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ leading_coefficient
leading_monomial
remove_leading_term
remove_monomials
filter_terms
OfDegree
monic
map_coefficients
map_coefficients!
Expand Down
46 changes: 46 additions & 0 deletions src/polynomial.jl
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,52 @@ function remove_monomials(
return q
end

"""
function filter_terms(f::Function, p::AbstractPolynomialLike)

Filter the polynomial `p` by only keep the terms `t` such that `f(p)` is
`true`.

See also [`OfDegree`](@ref).

### Examples

```julia
julia> p = 1 - 2x + x * y - 3y^2 + x^2 * y
1 - 2x - 3y² + xy + x²y

julia> filter_terms(OfDegree(2), p)
-3y² + xy

julia> filter_terms(!OfDegree(2), p)
1 - 2x + x²y

julia> filter_terms(!OfDegree(0:2), p)
x²y

julia> filter_terms(iseven ∘ coefficient, p)
-2x
```
"""
function filter_terms(f::F, p::AbstractPolynomialLike) where {F<:Function}
return polynomial(filter(f, terms(p)), SortedUniqState())
end

"""
struct OfDegree{D} <: Function
degree::D
end

A function `d::OfDegree` is such that `d(t)` returns
`degree(t) == d.degree`. Note that `!d` creates the negation.
See also [`filter_terms`](@ref).
"""
struct OfDegree{D} <: Function
degree::D
end

(d::OfDegree)(mono::AbstractTermLike) = in(degree(mono), d.degree)

"""
monic(p::AbstractPolynomialLike)

Expand Down
7 changes: 6 additions & 1 deletion test/polynomial.jl
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,12 @@ const MP = MultivariatePolynomials
@test transpose(x + y) == x + y
@test transpose([1 2; 3 4] * x) == [1 3; 2 4] * x

@test remove_monomials(4x^2 * y + x * y + 2x, [x * y]) == 4x^2 * y + 2x
p = 4x^2 * y + x * y + 2x
@test remove_monomials(p, [x * y]) == 4x^2 * y + 2x
@test filter_terms(OfDegree(2), 4x^2 * y + x * y + 2x) == x * y
@test filter_terms(!OfDegree(2), 4x^2 * y + x * y + 2x) == 4x^2 * y + 2x
@test filter_terms(iseven ∘ MP.coefficient, 4x^2 * y + x * y + 2x) ==
4x^2 * y + 2x

@test_throws InexactError push!([1], x + 1)

Expand Down
Loading