Skip to content
This repository was archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
20191: cases() function
Browse files Browse the repository at this point in the history
  • Loading branch information
rwst committed Aug 19, 2017
1 parent effcedb commit 1929337
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/sage/functions/all.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
abs_symbolic, sqrt, log_gamma,
gamma_inc, incomplete_gamma, gamma_inc_lower,
arg, real_part, real, frac,
imag_part, imag, imaginary, conjugate)
imag_part, imag, imaginary, conjugate, cases)

from .log import (exp, exp_polar, log, ln, polylog, dilog, lambert_w, harmonic_number)

Expand Down
91 changes: 91 additions & 0 deletions src/sage/functions/other.py
Original file line number Diff line number Diff line change
Expand Up @@ -2580,3 +2580,94 @@ def _print_latex_(self, ex, var, to, direction=''):

symbolic_limit = Function_limit()


class Function_cases(GinacFunction):
"""
Formal function holding ``(condition, expression)`` pairs.
Numbers are considered conditions with zero being ``False``.
A true condition marks a default value. The function is not
evaluated as long as it contains a relation that cannot be
decided by Pynac.
EXAMPLES::
sage: ex = cases([(x==0, pi), (True, 0)]); ex
cases(((x == 0, pi), (1, 0)))
sage: ex.subs(x==0)
pi
sage: ex.subs(x==2)
0
sage: ex + 1
cases(((x == 0, pi), (1, 0))) + 1
sage: _.subs(x==0)
pi + 1
The first encountered default is used, as well as the first relation
that can be trivially decided::
sage: cases(((True, pi), (True, 0)))
pi
sage: _ = var('y')
sage: ex = cases(((x==0, pi), (y==1, 0))); ex
cases(((x == 0, pi), (y == 1, 0)))
sage: ex.subs(x==0)
pi
sage: ex.subs(x==0, y==1)
pi
"""
def __init__(self):
"""
EXAMPLES::
sage: loads(dumps(cases))
cases
"""
GinacFunction.__init__(self, "cases")

def __call__(self, l, **kwargs):
"""
EXAMPLES::
sage: ex = cases([(x==0, pi), (True, 0)]); ex
cases(((x == 0, pi), (1, 0)))
TESTS::
sage: cases()
Traceback (most recent call last):
...
TypeError: __call__() takes exactly 2 arguments (1 given)
sage: cases(x)
Traceback (most recent call last):
...
RuntimeError: cases argument not a sequence
"""
return GinacFunction.__call__(self,
SR._force_pyobject(l), **kwargs)

def _print_latex_(self, l, **kwargs):
r"""
EXAMPLES::
sage: ex = cases([(x==0, pi), (True, 0)]); ex
cases(((x == 0, pi), (1, 0)))
sage: latex(ex)
\begin{cases}{\pi} & {x = 0}\\{0} & {1}\end{cases}
"""
if not isinstance(l, (list, tuple)):
raise ValueError("cases() argument must be a list")
str = r"\begin{cases}"
for pair in l:
left = None
if (isinstance(pair, tuple)):
right,left = pair
else:
right = pair
str += r"{%s} & {%s}\\" % (latex(left), latex(right))
print(str[:-2] + r"\end{cases}")

cases = Function_cases()

0 comments on commit 1929337

Please sign in to comment.