help-bison
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

More elegant way to parse this?


From: Joe Nelson
Subject: More elegant way to parse this?
Date: Sun, 14 Mar 2021 00:11:39 -0600

I wrote a parser for Roman numerals, and it seems to work for whatever
numbers I throw at it. However, there are two things I don't like: a
bunch of s/r conflicts, and the double recursion "number number".

Anyone know a way to keep it concise but avoid the warnings and
inefficiency?

Parser
======

%{
#include <stdio.h>

int yyerror(const char *s);
int yylex(void);
%}

%token I V X L C D M

%%

result :
  number { printf("%d\n", $1); }

number :
  subtracter
| number number { $$ = $1 + $2; }
| numeral
;

subtracter :
  I V { $$ = $2 - $1; }
| I X { $$ = $2 - $1; }
| X L { $$ = $2 - $1; }
| X C { $$ = $2 - $1; }
| C M { $$ = $2 - $1; }

numeral : I | V | X | L | C | D | M;


Scanner
=======

%{
#include "roman.tab.h"

extern int yylval;
%}

%%

I { yylval = 1;    return I; }
V { yylval = 5;    return V; }
X { yylval = 10;   return X; }
L { yylval = 50;   return L; }
C { yylval = 100;  return C; }
D { yylval = 500;  return D; }
M { yylval = 1000; return M; }

\n ;
.  { return *yytext; }



reply via email to

[Prev in Thread] Current Thread [Next in Thread]