Hello, World! – using Predefined

Here is a simple “Hello, World!” Mathics3 function.

from mathics.builtin.base import Predefined
from mathics.core.atom import String

class Hello(Predefined):
  def evaluate(self, evaluation: Evaluation) -> String:
    return String(f"Hello, World!")

Add the above at the end to a file in mathics.builtin like system.py,

Later on, we will show how to add code without modify the Mathics3 core, but for now we’ll start simple.

Now start mathics from the Mathics3 source tree:

$ python mathics/main.py
Mathics3 6.0.0
...
In[1]:= Hello
Out[1]= Hello, World!

Now let’s go over the code. For a Symbol Hello we define a Python Class of type Predefined. Predefined is perhaps the most primitive class that is used for adding Mathics3 Symbols.

In that class you define a method evaluate(self, evaluation) which is what will get called when the Symbol is evaluated. The evaluation parameter contains the evaluation environment that can be used to get definitions of variables and other things that may be needed to perform the function.

However here all we do is return a Mathics3 string, so we don’t need to use what is in evaluation.

The return value of a Mathics3 function should be some sort of superclass of BaseElement Class. A String is a subclass of the Atom Class which in turn is a subclass of the BaseElement. You can also return the None value, in which case the expression is unchanged.

Next: