Skip to content

Commit 14b5263

Browse files
authored
Merge pull request #113 from JuliaSymbolics/s/methods
eval_number_methods on your own types
2 parents e32fa58 + 498649e commit 14b5263

File tree

1 file changed

+37
-13
lines changed

1 file changed

+37
-13
lines changed

src/methods.jl

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,49 @@ const monadic = [deg2rad, rad2deg, transpose, -, conj, asind, log1p, acsch, acos
22

33
const diadic = [+, -, max, min, *, /, \, hypot, atan, mod, rem, ^]
44

5+
const previously_declared_for = Set([])
56
# TODO: keep domains tighter than this
6-
for f in diadic
7-
@eval promote_symtype(::$(typeof(f)),
8-
T::Type{<:Number},
9-
S::Type{<:Number}) = promote_type(T, S)
10-
11-
for T in [Sym, Term]
12-
for S in [Sym, Term]
13-
@eval (::$(typeof(f)))(a::$T, b::$S) = term($f, a, b)
7+
function number_methods(T, rhs1, rhs2)
8+
exprs = []
9+
for f in diadic
10+
for S in previously_declared_for
11+
push!(exprs, quote
12+
(f::$(typeof(f)))(a::$T, b::$S) = $rhs2
13+
(f::$(typeof(f)))(a::$S, b::$T) = $rhs2
14+
end)
1415
end
15-
@eval begin
16-
(::$(typeof(f)))(a::$T, b::Real) = term($f, a, b)
17-
(::$(typeof(f)))(a::Real, b::$T) = term($f, a, b)
18-
(::$(typeof(f)))(a::$T, b::Number) = term($f, a, b)
19-
(::$(typeof(f)))(a::Number, b::$T) = term($f, a, b)
16+
17+
# TODO: modularize and make another macro?
18+
expr = quote
19+
(f::$(typeof(f)))(a::$T, b::$T) = $rhs2
20+
(f::$(typeof(f)))(a::$T, b::Real) = $rhs2
21+
(f::$(typeof(f)))(a::Real, b::$T) = $rhs2
22+
(f::$(typeof(f)))(a::$T, b::Number) = $rhs2
23+
(f::$(typeof(f)))(a::Number, b::$T) = $rhs2
2024
end
25+
26+
push!(exprs, expr)
27+
end
28+
29+
for f in monadic
30+
push!(exprs, :((f::$(typeof(f)))(a::$T) = $rhs1))
2131
end
32+
push!(exprs, :(push!($previously_declared_for, $T)))
33+
Expr(:block, exprs...)
2234
end
2335

36+
macro number_methods(T, rhs1, rhs2)
37+
number_methods(T, rhs1, rhs2) |> esc
38+
end
39+
40+
@number_methods(Sym, term(f, a), term(f, a, b))
41+
@number_methods(Term, term(f, a), term(f, a, b))
42+
43+
for f in diadic
44+
@eval promote_symtype(::$(typeof(f)),
45+
T::Type{<:Number},
46+
S::Type{<:Number}) = promote_type(T, S)
47+
end
2448
promote_symtype(::typeof(rem2pi), T::Type{<:Number}, mode) = T
2549
Base.rem2pi(x::Symbolic, mode::Base.RoundingMode) = term(rem2pi, x, mode)
2650

0 commit comments

Comments
 (0)