Skip to content

Commit 142ea18

Browse files
authored
Merge pull request #251 from JuliaSymbolics/myb/oc
Overload `occursin`
2 parents c2d4e01 + ef09a8d commit 142ea18

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/api.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,24 @@ function substitute(expr, dict; fold=true)
6060
expr
6161
end
6262
end
63+
64+
"""
65+
occursin(needle::Symbolic, haystack::Symbolic)
66+
67+
Determine whether the second argument contains the first argument. Note that
68+
this function doesn't handle associativity, commutativity, or distributivity.
69+
"""
70+
Base.occursin(needle::Symbolic, haystack::Symbolic) = _occursin(needle, haystack)
71+
Base.occursin(needle, haystack::Symbolic) = _occursin(needle, haystack)
72+
Base.occursin(needle::Symbolic, haystack) = _occursin(needle, haystack)
73+
function _occursin(needle, haystack)
74+
isequal(needle, haystack) && return true
75+
76+
if istree(haystack)
77+
args = arguments(haystack)
78+
for arg in args
79+
occursin(needle, arg) && return true
80+
end
81+
end
82+
return false
83+
end

test/basics.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,13 @@ end
132132
@test substitute(exp(a), Dict(a=>2)) exp(2)
133133
end
134134

135+
@testset "occursin" begin
136+
@syms a b c
137+
@test occursin(a, a + b)
138+
@test !occursin(sin(a), a + b + c)
139+
@test occursin(sin(a), a * b + c + sin(a^2 * sin(a)))
140+
end
141+
135142
@testset "printing" begin
136143
@syms a b c
137144
@test repr(a+b) == "a + b"

0 commit comments

Comments
 (0)