
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "examples/calc.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_examples_calc.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_examples_calc.py:


Basic calculator
================

A simple example of a REPL calculator

This example shows how to write a basic calculator with variables.

.. GENERATED FROM PYTHON SOURCE LINES 9-83

.. code-block:: Python

    from lark import Lark, Transformer, v_args


    try:
        input = raw_input   # For Python2 compatibility
    except NameError:
        pass


    calc_grammar = """
        ?start: sum
              | NAME "=" sum    -> assign_var

        ?sum: product
            | sum "+" product   -> add
            | sum "-" product   -> sub

        ?product: atom
            | product "*" atom  -> mul
            | product "/" atom  -> div

        ?atom: NUMBER           -> number
             | "-" atom         -> neg
             | NAME             -> var
             | "(" sum ")"

        %import common.CNAME -> NAME
        %import common.NUMBER
        %import common.WS_INLINE

        %ignore WS_INLINE
    """


    @v_args(inline=True)    # Affects the signatures of the methods
    class CalculateTree(Transformer):
        from operator import add, sub, mul, truediv as div, neg
        number = float

        def __init__(self):
            self.vars = {}

        def assign_var(self, name, value):
            self.vars[name] = value
            return value

        def var(self, name):
            try:
                return self.vars[name]
            except KeyError:
                raise Exception("Variable not found: %s" % name)


    calc_parser = Lark(calc_grammar, parser='lalr', transformer=CalculateTree())
    calc = calc_parser.parse


    def main():
        while True:
            try:
                s = input('> ')
            except EOFError:
                break
            print(calc(s))


    def test():
        print(calc("a = 1+2"))
        print(calc("1+a*-3"))


    if __name__ == '__main__':
        # test()
        main()


.. _sphx_glr_download_examples_calc.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: calc.ipynb <calc.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: calc.py <calc.py>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
