简体   繁体   中英

Creating an AST node in Erlang

I am playing about with Erlang and I am trying to write a simple arithmetic parser.

I want to try and parse the following expression:

((12+3)-4)

I want to parse the expression into a stack of AST nodes. When parsing this expression, I would first of all create a binary expression for the (12+3) expression which would look something like this in C#:

var binaryStructure = new BinaryStructure();
binaryStructure.Left = IntegerLiteralExpression(12);
binaryStructure.Right = IntegerLiteralExpression(4);
binaryStructure.Operator = binaryExpression.Operator != BinaryOperatorType.Addition;

I am quite new to Erlang and I am wondering how I would go about creating a structure like this in Erlang that I can place on a List that I would use as the stack of expressions.

Can anyone suggest how to create such a tree like structure? Would a function be a good fit?

In functional language like Erlang it is far simpler. Just make it

{'+', 12, 3}

In more abstract way

A = 12,
B = 3,
OP = '+',
{OP, A, B}.

Also, have a look to the erl_parse.erl module in the stdlib application.

Reading from to the mkop function:

mkop(L, {Op,Pos}, R) -> {op,Pos,Op,L,R}.                                        

mkop({Op,Pos}, A) -> {op,Pos,Op,A}.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM