Skip to content

Commit

Permalink
Overload occursin
Browse files Browse the repository at this point in the history
  • Loading branch information
YingboMa committed Mar 28, 2021
1 parent f6d592c commit ef09a8d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/api.jl
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,24 @@ function substitute(expr, dict; fold=true)
expr
end
end

"""
occursin(needle::Symbolic, haystack::Symbolic)
Determine whether the second argument contains the first argument. Note that
this function doesn't handle associativity, commutativity, or distributivity.
"""
Base.occursin(needle::Symbolic, haystack::Symbolic) = _occursin(needle, haystack)
Base.occursin(needle, haystack::Symbolic) = _occursin(needle, haystack)
Base.occursin(needle::Symbolic, haystack) = _occursin(needle, haystack)
function _occursin(needle, haystack)
isequal(needle, haystack) && return true

if istree(haystack)
args = arguments(haystack)
for arg in args
occursin(needle, arg) && return true
end
end
return false
end
7 changes: 7 additions & 0 deletions test/basics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,13 @@ end
@test substitute(exp(a), Dict(a=>2)) exp(2)
end

@testset "occursin" begin
@syms a b c
@test occursin(a, a + b)
@test !occursin(sin(a), a + b + c)
@test occursin(sin(a), a * b + c + sin(a^2 * sin(a)))
end

@testset "printing" begin
@syms a b c
@test repr(a+b) == "a + b"
Expand Down

0 comments on commit ef09a8d

Please sign in to comment.