# mathy_core¶

*Parse text into trees, visualize them, and make them dance by your rules.*

Mathy includes a Computer Algebra System (or CAS). Its job is to turn text into math trees that can be examined and manipulated by a multi-step process:

- Tokenize the text into a list of
`type`

/`value`

pairs - Parse the token list into an Expression tree
- Modify the tree by applying a transformation rule to it.

## Requirements¶

- Python 3.6+

## Installation¶

```
$ pip install mathy_core
```

## Examples¶

### Arithmetic¶

To understand how Mathy's CAS components work, let's add some numbers and assert that the result is what we think it should be.

```
from mathy_core import ExpressionParser
expression = ExpressionParser().parse("4 + 2")
assert expression.evaluate() == 6
```

### Variables Evaluation¶

Mathy can also deal with expressions that have variables.

When an expression has variables in it, you can evaluate it by providing the "context" to use:

```
from mathy_core import ExpressionParser, MathExpression
expression: MathExpression = ExpressionParser().parse("4x + 2y")
assert expression.evaluate({"x": 2, "y": 5}) == 18
```

### Tree Transformations¶

Mathy can also transform the parsed Expression trees using rules that change the tree structure without altering the value it outputs when you call `evaluate()`

.

```
from mathy_core import ExpressionParser
from mathy_core.rules import DistributiveFactorOutRule
input = "4x + 2x"
output = "(4 + 2) * x"
parser = ExpressionParser()
input_exp = parser.parse(input)
output_exp = parser.parse(output)
# Verify that the rule transforms the tree as expected
change = DistributiveFactorOutRule().apply_to(input_exp)
assert str(change.result) == output
# Verify that both trees evaluate to the same value
ctx = {"x": 3}
assert input_exp.evaluate(ctx) == output_exp.evaluate(ctx)
```

## Contributors¶

Mathy Core wouldn't be possible without the contributions of the following people:

This project follows the all-contributors specification. Contributions of any kind are welcome!