Mast: a Math AST for Golang
Because Go does not support operator overloading, most numerical libraries are
messy to use. Mast is an attempt to write a domain-specific language for math,
so that code can be written in a more simple way.
If it helps, think regular expressions, but for
algebra.
mast.Eval("x = A' * b + c", &x, &A, &b, &c)
Transpose(&aT, &A)
Times(&Atb, &At, &b)
Plus(&x, &Atb, &c)
Parser
Mast mostly exists to create parsers for math-like languages. To use it,
first create a *mast.Parser object, configuring the various operations
and their precidence.
type Parser struct {
Operators []Prec
Groups []Group
AdjacentIsApplication bool
}
Then you invoke the (p *mast.Parser).Parse(string) (*mast.Equation, error)
function.
func (p Parser) Parse(source string) (e *Equation, error) {
Example
Suppose we want to make a basic calculator parser. First, define which
operations and grouping operators we want to support:
integers := &mast.Parser{
Groups: []Group{
{"(", ")"},
},
Operators: []Prec{
{[]string{"+", "-"}, InfixLeft},
{[]string{"*", "/", "%"}, InfixLeft},
{[]string{"-", "+"}, Prefix},
},
}
To parse a string using this language, invoke
(p *mast.Parser) Parse(string) (*mast.Equation, error)
with the source code
to evaluate. For example, if we run:
tree, err := integers.Parse("y = (-a) * b + c")
fmt.Printf("tree: %v\n", tree)
then err
will be nil
and tree
will be as follows:
tree := &Equation{
Left: &Var{"y"},
Right: &Binary{
Op: "+",
Left: &Binary{
Op: "*",
Left: &Unary{
Op: "-",
Elem: &Var{"a"},
},
Right: &Var{"b"},
}
Right: &Var{"c"}
}
}
By iterating over the tree, your DSL can evaluate the mathematical
expression while maintaining type integrity.
Evaluator
Mast includes a toy evaluator that handles matrices as [][]float64.
To use it, invoke the Eval(code string, args ...interface{}) error
function, passing pointers to the respective arguments.
func Eval(code string, args ...interface{}) error {
Think %
-arguments to fmt.Printf
. To make setting up variables easier,
arguments can be specified in three ways:
- a
[][]float64
for an n x m
matrix; - a
[]float64
for an 1 x n
column vector; or - a
float64
, for a 1 x 1
scalar.
All other types panic.
Example
Suppose we want to compute a linear transform (multiplying a vector by
a matrix, and adding a vector). First, we set up the variables to compute:
A := [][]float64{
[]float64{1, 2},
}
x := []float64{3, 4}
b := 5.0
y := 0
Once those are set up, the computation is fairly easy.
if err := mast.Eval("y = A * x + b", &y, &A, &x, &b); err != nil {
handleError(err)
return
}
The result is then available in y.
License
This code is covered under the MIT license.
Copyright (c) 2016 Jeremy Archer
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.