0

My question is kinda simple, i suppose. Here is my code,

%{

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

int yylex(void);
void yyerror(char const *c);

int yywarp(){
    return 1;
}
%}

%token LETTER MID

%%
input: {printf("Enter the polindrom:\n");}
    | input line;

line:   anal '\n'   {printf("good\n\n");}
    | error '\n'    {yyerrok;}
    ;

anal:   MID MID {
        printf("%d %d\n", $1, $2);

        if($1!=$2)
            YYERROR;
        }

    |LETTER anal LETTER {

        printf("%d %d\n", $1, $3);

        if($1!=$3)
            YYERROR;
        }
    ;

%%
int yylex(void)
{
    int c;
    char a[10];

    c = getchar();

    if(c == 'a'){
        yylval = c;
        return MID;
    }
    if(isalpha(c)){
        yylval = c;
        return LETTER;
    }

    if(c == EOF)
        return 0;

    return c;
}

void yyerror(char const *c)
{
    fprintf(stderr, "%s\n", c);
}

int main(){
    return(yyparse());
}

As you can see, MID returns only when you input 'a'. My question is: how to get real middle element? The task is to recognize palindromes using YACC. But i think my teacher won't accept it if i just use "for" cycle for it.

bitcell
  • 921
  • 8
  • 16

1 Answers1

1

The language of palindromes is not LR(1), so yacc cannot generate a parser for it without an oracle that lets it know where the middle of the string is. Your example includes such an oracle; it is easy to do if the middle letter (or pair of letters) have a distinct value. If that is part of the problem specification, then you are basically on the right track.

bison could parse palindromes if you ask it to generate a GLR parser instead of an LALR(1) parser. The fact that you say yacc rather than bison suggests that this is not an appropriate solution, and it is not in general an appropriate solution because GLR parsers are not linear-time with grammars like this, whereas an obvious linear-time parsing solution exists.

If all else fails, you could simply parse the input into a list of characters, and check to see if it is a palindrome in the final reduction action.

rici
  • 234,347
  • 28
  • 237
  • 341