Skip to content

Commit 91a1afc

Browse files
committed
more optimizations
1 parent 102253f commit 91a1afc

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

src/polyform.jl

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,7 @@ end
260260
add_divs(x::Div, y::Div) = (x.num * y.den + y.num * x.den) / (x.den * y.den)
261261
add_divs(x::Div, y) = (x.num + y * x.den) / x.den
262262
add_divs(x, y::Div) = (x * y.den + y.num) / y.den
263+
add_divs(x, y) = x + y
263264

264265
"""
265266
simplify_fractions(x)
@@ -272,24 +273,21 @@ function simplify_fractions(x)
272273

273274
!needs_div_rules(x) && return x
274275

275-
isdiv(x) = x isa Div
276+
sdiv(a) = a isa Div ? simplify_div(a) : a
276277

277-
rules = [@rule ~x::isdiv => simplify_div(~x)
278-
@acrule ~a::isdiv + ~b::isdiv => add_divs(~a,~b)]
279-
280-
Fixpoint(Postwalk(RestartedChain(rules)))(x)
278+
Postwalk(sdiv quick_cancel)(Postwalk(add_with_div)(x))
281279
end
282280

283-
function add_with_div(x)
284-
(!istree(x) || operation(x) != (+)) && return nothing
281+
function add_with_div(x, flatten=true)
282+
(!istree(x) || operation(x) != (+)) && return x
285283
aa = unsorted_arguments(x)
286-
!any(a->a isa Div, aa) && return nothing # no rewrite necessary
284+
!any(a->a isa Div, aa) && return x # no rewrite necessary
287285

288286
divs = filter(a->a isa Div, aa)
289287
nondivs = filter(a->!(a isa Div), aa)
290288
nds = isempty(nondivs) ? 0 : +(nondivs...)
291-
292-
return quick_cancel(add_divs(reduce(quick_canceladd_divs, divs), nds))
289+
d = reduce(quick_canceladd_divs, divs)
290+
flatten ? quick_cancel(add_divs(d, nds)) : d + nds
293291
end
294292
"""
295293
flatten_fractions(x)
@@ -302,7 +300,7 @@ julia> flatten_fractions((1+(1+1/a)/a)/a)
302300
```
303301
"""
304302
function flatten_fractions(x)
305-
Fixpoint(Postwalk(PassThrough(add_with_div)))(x)
303+
Fixpoint(Postwalk(add_with_div))(x)
306304
end
307305

308306
function fraction_iszero(x)

0 commit comments

Comments
 (0)