Skip to content

Commit 67af844

Browse files
committed
Fix use of Piecewise in If
1 parent 794371a commit 67af844

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

mathics/builtin/arithmetic.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,11 @@ def to_sympy(self, expr, **kwargs):
372372
sympy_cond = False
373373
if sympy_cond is None:
374374
sympy_cond = cond.to_sympy(**kwargs)
375+
# See similar code and comment in mathics.builtin.procedural.If
376+
# TODO: consider adding .is_Symbol (as with If) so that this
377+
# can be used for compilation. I tried that but it invalidated
378+
# doctest 1876 in Simplify which depends on ConditionalExpression
379+
# not getting rewritten, so may need update that secion of doc?
375380
if not (sympy_cond.is_Relational or sympy_cond.is_Boolean):
376381
return
377382

mathics/builtin/procedural.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,20 @@ def to_sympy(self, expr, **kwargs):
455455
sympy_cond = expr.elements[0].to_sympy(**kwargs)
456456
sympy_true = expr.elements[1].to_sympy(**kwargs)
457457
sympy_false = expr.elements[2].to_sympy(**kwargs)
458-
return sympy.Piecewise((sympy_true, sympy_cond), (sympy_false, True))
458+
if sympy_cond is None:
459+
return
460+
# sympy.Piecewise is is picky as to what type of conds it will accept,
461+
# allowing Boolean, Relational, and Symbol (as an honorary Boolean,
462+
# accompanied by a comment in the code that this isn't really correct).
463+
# Seems an attempt at early typechecking, but maybe too restrictive -
464+
# what about Exprs in general that might or might not evaluate to Boolean?
465+
# See similar code in mathics.builtin.arithmetic.ConditionalExpression.
466+
if (
467+
sympy_cond.is_Boolean
468+
or sympy_cond.is_Relational
469+
or sympy_cond.is_Symbol
470+
):
471+
return sympy.Piecewise((sympy_true, sympy_cond), (sympy_false, True))
459472

460473

461474
class Interrupt(Builtin):

0 commit comments

Comments
 (0)