File tree Expand file tree Collapse file tree 3 files changed +54
-1
lines changed Expand file tree Collapse file tree 3 files changed +54
-1
lines changed Original file line number Diff line number Diff line change @@ -81,6 +81,8 @@ leading_coefficient
8181leading_monomial
8282remove_leading_term
8383remove_monomials
84+ filter_terms
85+ OfDegree
8486monic
8587map_coefficients
8688map_coefficients!
Original file line number Diff line number Diff line change @@ -474,6 +474,52 @@ function remove_monomials(
474474 return q
475475end
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
Original file line number Diff line number Diff 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 (4 x^ 2 * y + x * y + 2 x, [x * y]) == 4 x^ 2 * y + 2 x
152+ p = 4 x^ 2 * y + x * y + 2 x
153+ @test remove_monomials (p, [x * y]) == 4 x^ 2 * y + 2 x
154+ @test filter_terms (OfDegree (2 ), 4 x^ 2 * y + x * y + 2 x) == x * y
155+ @test filter_terms (! OfDegree (2 ), 4 x^ 2 * y + x * y + 2 x) == 4 x^ 2 * y + 2 x
156+ @test filter_terms (iseven ∘ MP. coefficient, 4 x^ 2 * y + x * y + 2 x) ==
157+ 4 x^ 2 * y + 2 x
153158
154159 @test_throws InexactError push! ([1 ], x + 1 )
155160
You can’t perform that action at this time.
0 commit comments