0

I have a simple struct called Polyn like this:

typedef struct Polyn {
  int sign;
  int coeff;
  int exp;
  struct Polyn *next;
} Polyn;

In my bison grammar for recursively building polynomials I only get the first and last element. I use these functions to add and make terms with the Polyn struct:


Polyn *addmonomial(Polyn *pol, Polyn *monom) {
    pol -> next = monom;
    return pol; 
}

So for a=1x2+2x+3, it only gives me 1x2+3. The recursion will only build the first and last elements. I don't know whether to change the return value of the add function or how to change the grammar so the middle terms are included. It seems like the problem is $1 in my last two recursive rules is always the first term and doesn't become the middle terms. I need to return the first term for my other grammar rules but also build the polynomial.

    |poln T_PLUS poln   { $$ = addmonomial($1, $3);}
    |poln T_MINUS poln  { Polyn *p2n = negate($3); $$ = addmonomial($1, p2n); }
sidthekid
  • 7
  • 3

2 Answers2

0
Polyn *addmonomial(Polyn *pol, Polyn *monom) {
    pol -> next = monom;
    return pol; 
}

This will override the existing value of next if pol already has a next value. So if pol represent the expression 1x2+2x and monom represents 3, then the 2x part will be overridden by 1.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • How do i change the grammar to make it work? – sidthekid Nov 30 '20 at 16:41
  • i need to return the first term after all the recursive calls, but i also need each next value to point to the next term going all the way to the last term – sidthekid Nov 30 '20 at 16:44
  • @sidthekid It's not about the grammar - the grammar is fine. You'll need to fix your `addmonomial` function. – sepp2k Nov 30 '20 at 16:49
  • how bro? if i return monom instead of pol, then it forgets the first term and all the middle terms. it sets the pointer correctly but only returns the last term. Do i make monom point to pol? – sidthekid Nov 30 '20 at 16:54
  • @sidthekid You can do that if the order doesn't matter (that is, if you don't care that `foo + bar` will come out as `bar + foo`) - as long as `monom` is indeed monomial, it's `next` pointer will be `NULL` and thus safe to overwrite. Or you could add `monom` to the actual end of `pol` by following the `next` pointer until it is `NULL` - just like appending to a singly linked list, which is essentially what this is. – sepp2k Nov 30 '20 at 16:58
0

Get rid of your addmonomial function and instead use an addpolynomial function. While you're at it, get rid of the sign field, it is redundant with the sign of the coeff field. You might also want to make the coeff field a double rather than an int.

Your addpolynomial function should merge the two linked lists of terms, combining terms with the same exponent. Probably easiest if you always keep them sorted in exponent order.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226