Hello,
I am trying out the happy parser.
Take the second example Binary to Decimal given on the happy site: http://www.haskell.org/happy/doc/html/sec-AttributeGrammarExample.html
This example computes the decimal value equivalent to the given binary string.
I want to modify it so that along with the decimal value, it should compute a list of data values, like MyLeft, MyRight.
I have modified the grammar given on the site as shown below (in the end).
What I want to do is generate a list of MyLeft, MyRight such that MyLeft denotes 0 and MyRight denotes 1.
So, if my input is "1011\n" then I expect the list attribute to be:
[MyRight, Myleft, MyRight, MyRight]
The happy compiles this thing without any problem, ghci compiles and loads it correctly. But when I run the following command I always get only the decimal value and not the list:
So my questions are:
- How shall one compute, access multiple attributes in happy first? (use in Haskell code, write to file etc)
- How shall one access any one or multiple of the computed attributes in GHCi then?
- Am I computing the list correctly?
Thanks in advance.
kak
Here is my happy grammar code:
-----------------------------
{
module BitsParser (parse) where
test = parse "1011\n"
-- how to write the list attribute to a file here?
data Dirs = MyLeft | MyRight deriving Show
fun a b = a^b
}
%tokentype { Char }
%token minus { '-' }
%token plus { '+' }
%token one { '1' }
%token zero { '0' }
%token newline { '\n' }
%attributetype { Attrs }
%attribute value { Integer }
%attribute pos { Int }
%attribute list { [Dirs] }
%name parse start
%%
start
: num newline { $$ = $1 }
num
: bits { $$ = $1 ; $1.pos = 0 ; $1.list = [] }
| plus bits { $$ = $2 ; $2.pos = 0 ; $2.list = [] }
| minus bits { $$ = negate $2; $2.pos = 0 ; $2.list = [] }
bits
: bit { $$ = $1
; $1.pos = $$.pos ; $1.list = $$.list
}
| bits bit { $$ = $1 + $2 ; $$.list = $1.list ++ $2.list
; $1.pos = $$.pos + 1
; $2.pos = $$.pos
}
bit
: zero { $$ = 0 ; $$.list = [MyLeft] }
| one { $$ = fun 2 ($$.pos) ; $$.list = [MyRight] }
{
happyError = error "parse error"
}