Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve switch doc #958

Merged
merged 3 commits into from
Jan 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions mathics/builtin/procedural.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,15 @@ class Switch(Builtin):
>> Switch[2, 1]
: Switch called with 2 arguments. Switch must be called with an odd number of arguments.
= Switch[2, 1]


Notice that 'Switch' evaluates each pattern before it against \
$expr$, stopping after the first match:
>> a:=(Print["a->p"];p); b:=(Print["b->q"];q);
>> Switch[p,a,1,b,2]
| a->p
= 1
>> a=.; b=.;
"""

summary_text = "switch based on a value, with patterns allowed"
Expand All @@ -486,6 +495,9 @@ def eval(self, expr, rules, evaluation):
evaluation.message("Switch", "argct", "Switch", len(rules) + 1)
return
for pattern, value in zip(rules[::2], rules[1::2]):
# The match is done against the result of the evaluation
# of `pattern`. HoldRest allows to evaluate the patterns
# just until a match is found.
if match(expr, pattern.evaluate(evaluation), evaluation):
return value.evaluate(evaluation)
# return unevaluated Switch when no pattern matches
Expand Down
Loading