Storing a list in an expression list

Christopher Wright dhasenan at gmail.com
Wed Jun 27 17:27:45 PDT 2007


Lurker #5 wrote:
> Hi,
> 
> I'm starting with D and I want to use it for a project on skool. I want to write a new scriptiing language but I dont' know how to store a list on my expression list.
> 
> I have this structure:
> 
> class Node(T) {
> public:
>   T value
>   Node!(T) left;
>   Node!(T) right;
> 
>   // Constructors...
> }
> 
> And I use it like this:
> 
> // a = b + c;
> Node!(string) expression = new Node!(string)("=", 
> new Node!(string)("a", 
> new Node!(string)("=", 
> new Node!(string)("b", 
> new Node!(string)("c")));
> 
> Which gives me smth like:
> 
>   =
> a  +
>   b  c
> 
> But i dont' know how to store a list of parameters:
> 
> func(1, 2, 3);
> 
> expression = new Node!(string)("(", 
> new Node!(string)("func"),
> ... ???
> );
> 
> What do you suggest?
> 
> tnks

When I was in linguistics, we had an extreme paranoia about non-binary 
branching. So we would have done something more like:

---
enum NodeType { literal, parameter_list }
class Node(T) {
public:
   T value;
   NodeType type;
   Node!(T) left;
   Node!(T) right;

   // Constructors...
   this (T val) { value = val; }
   this (T val, Node!(T) left, Node!(T) right) {
     this.value = val;
     this.left = left;
     this.right = right;
   }
   this (NodeType type, Node!(T) left, Node!(T) right) {
     this.type = type;
     this.left = left;
     this.right = right;
   }
}

expression = new Node!(string)("(",
   new Node!(string)("func"),
   new Node!(string)(NodeType.parameter_list,
     new Node!(string)("1"),
     new Node!(string)(NodeType.parameter_list,
       new Node!(string)("2"),
       new Node!(string)("3")
     )
   )
);
---

That, or use varargs.

The benefit to using the method I outlined is that it's closer to 
Chomsky Normal Form, which makes for simpler parsing in some cases. It 
helps as a guarantee of being context-free, at least. Though since it's 
simple to switch from varargs to the tree form, it's a matter of 
whatever saves you work.

Though your grammar is not in CNF; all the nonterminal rules you 
provided are of the form A -> BaC. You could alter that easily enough, 
but there's probably no practical benefit.



More information about the Digitalmars-d mailing list