[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Give me an example please!!!
From: |
Hans Aberg |
Subject: |
Re: Give me an example please!!! |
Date: |
Fri, 7 Jun 2002 01:10:38 +0200 |
At 11:51 -0500 2002/06/06, Javier Andres Mena Zapata wrote:
>Thank you, but I need to know how can I evaluate the expressions, that is,
>what are the ACTIONs. I've thinking about it, but i'm not sure...
You might write something like (including only the changes, actions in C++
pseudo-code):
%%
exp: prim '(' list_of_exp ')' { $$ = op_eval($1, $3); }
| number { $$ = $1; }
...
list_of_exp:
exp { $$ = list($1); }
| list_of_exp exp { $$ = $1.append($2); }
%%
Here, "op_eval" is function that takes the operator as the first argument,
the list of numbers as the second argument, evaluates it, and returns the
result. One can write like you suggested:
%union {
int number;
int operator; /* 0 to sum, 1 to substract, and * to multiply */
}
...
%%
prim:
'+' { $$ = 0; }
| '-' { $$ = 1; }
| '*' { $$ = 2; }
But it would mean that whenever you add a new operator, the function
op_eval must be made to recognize the new operator.
>> Your YYSTYPE must be able to store both a number and the operator type. So
>> you might use the %union feature (see Bison manual), one field of number
>> type X, and then perhaps your operators will have type (C++ pseudo-code)
>> X (*)(const &list<X>)
>
>I didn't understand this part (especially I don't know so much about
>the STL from C++).
Therefore, one might turn "op_eval" into something like the "foldr" type of
functions in Haskell <http://haskell.org>. The foldr function takes an
operator, an initial value, and by that extends the operator to all lists.
You then write functions that operate on lists:
int add(X (*)(const &list<X>));
...
and change to
%union {
int number;
int (*)(const &list<int>); /* operator on list */
}
and your code then becomes
exp: prim '(' list_of_exp ')' { $$ = (*$1)($3); }
| number { $$ = $1; }
prim:
'+' { $$ = &add; }
| '-' { $$ = ⊂ }
| '*' { $$ = &mult; }
Hans Aberg