Skip to content

Commit bd6b9e7

Browse files
committed
add Catch and Throw as builtins
1 parent b293853 commit bd6b9e7

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

mathics/builtin/control.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,3 +721,64 @@ def apply(self, evaluation):
721721
'Continue[]'
722722

723723
raise ContinueInterrupt
724+
725+
726+
class Catch(Builtin):
727+
"""
728+
<dl>
729+
<dt>'Catch[`expr`]'
730+
<dd> returns the argument of the first Throw generated in the evaluation of expr.
731+
732+
<dt>'Catch[`expr`, `form`]'
733+
<dd> returns value from the first Throw[`value`,`tag`] for which form matches `tag`.
734+
735+
<dt>'Catch[`expr`,`form`,`f`]'
736+
<dd> returns the argument of the first `Throw` generated in the evaluation of `expr`.
737+
</dl>
738+
739+
Exit to the enclosing Catch as soon as Throw is evaluated:
740+
<< Catch[r; s; Throw[t]; u; v]
741+
= t
742+
743+
Define a function that can "throw an exception":
744+
<< f[x_] := If[x > 12, Throw[overflow], x!]
745+
= ...
746+
The result of Catch is just what is thrown by Throw:
747+
<< Catch[f[1] + f[15]]
748+
= overflow
749+
<< Catch[f[1]+f[4]]
750+
= 24
751+
752+
"""
753+
754+
def apply(self, expr, form, f, evaluation):
755+
'Catch[expr_, form_:___, f__:Identity]'
756+
print("setting a Catch point")
757+
758+
759+
class Throw(Builtin):
760+
"""
761+
<dl>
762+
<dt>'Throw[`value`]'
763+
<dd> stops evaluation and returns `value` as the value of the nearest enclosing Catch.
764+
765+
<dt>'Catch[`value`, `tag`]'
766+
<dd> is caught only by `Catch[expr,form]`, where tag matches form.
767+
768+
</dl>
769+
770+
Using Throw can affect the structure of what is returned by a function:
771+
772+
<< NestList[#^2 + 1 &, 1, 7]
773+
= ...
774+
<< Catch[NestList[If[# > 1000, Throw[#], #^2 + 1] &, 1, 7]]
775+
= 458330
776+
777+
"""
778+
messages = {'nocatch': 'Uncaught `1` returned to top level.', }
779+
780+
def apply(self, value, tag, evaluation):
781+
'Throw[value_, tag__:Null]'
782+
print ("Throw")
783+
784+

0 commit comments

Comments
 (0)