Skip to content

Commit 79c141e

Browse files
authored
Add filter_terms (#287)
* Add filter_terms * Fix format
1 parent bfa750b commit 79c141e

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

docs/src/types.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ leading_coefficient
8181
leading_monomial
8282
remove_leading_term
8383
remove_monomials
84+
filter_terms
85+
OfDegree
8486
monic
8587
map_coefficients
8688
map_coefficients!

src/polynomial.jl

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,52 @@ function remove_monomials(
474474
return q
475475
end
476476

477+
"""
478+
function filter_terms(f::Function, p::AbstractPolynomialLike)
479+
480+
Filter the polynomial `p` by only keep the terms `t` such that `f(p)` is
481+
`true`.
482+
483+
See also [`OfDegree`](@ref).
484+
485+
### Examples
486+
487+
```julia
488+
julia> p = 1 - 2x + x * y - 3y^2 + x^2 * y
489+
1 - 2x - 3y² + xy + x²y
490+
491+
julia> filter_terms(OfDegree(2), p)
492+
-3y² + xy
493+
494+
julia> filter_terms(!OfDegree(2), p)
495+
1 - 2x + x²y
496+
497+
julia> filter_terms(!OfDegree(0:2), p)
498+
x²y
499+
500+
julia> filter_terms(iseven ∘ coefficient, p)
501+
-2x
502+
```
503+
"""
504+
function filter_terms(f::F, p::AbstractPolynomialLike) where {F<:Function}
505+
return polynomial(filter(f, terms(p)), SortedUniqState())
506+
end
507+
508+
"""
509+
struct OfDegree{D} <: Function
510+
degree::D
511+
end
512+
513+
A function `d::OfDegree` is such that `d(t)` returns
514+
`degree(t) == d.degree`. Note that `!d` creates the negation.
515+
See also [`filter_terms`](@ref).
516+
"""
517+
struct OfDegree{D} <: Function
518+
degree::D
519+
end
520+
521+
(d::OfDegree)(mono::AbstractTermLike) = in(degree(mono), d.degree)
522+
477523
"""
478524
monic(p::AbstractPolynomialLike)
479525

test/polynomial.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,12 @@ const MP = MultivariatePolynomials
149149
@test transpose(x + y) == x + y
150150
@test transpose([1 2; 3 4] * x) == [1 3; 2 4] * x
151151

152-
@test remove_monomials(4x^2 * y + x * y + 2x, [x * y]) == 4x^2 * y + 2x
152+
p = 4x^2 * y + x * y + 2x
153+
@test remove_monomials(p, [x * y]) == 4x^2 * y + 2x
154+
@test filter_terms(OfDegree(2), 4x^2 * y + x * y + 2x) == x * y
155+
@test filter_terms(!OfDegree(2), 4x^2 * y + x * y + 2x) == 4x^2 * y + 2x
156+
@test filter_terms(iseven MP.coefficient, 4x^2 * y + x * y + 2x) ==
157+
4x^2 * y + 2x
153158

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

0 commit comments

Comments
 (0)