Skip to content

Commit

Permalink
Add filter_terms (#287)
Browse files Browse the repository at this point in the history
* Add filter_terms

* Fix format
  • Loading branch information
blegat authored Dec 7, 2023
1 parent bfa750b commit 79c141e
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
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

0 comments on commit 79c141e

Please sign in to comment.