Question

I'm having a bit of difficulty parsing fractions in my treetop grammar.

My grammar looks like this

grammar Numbers
   rule number
        regular_number optional_frac {
               def value
                   [:number, text_value]
               end
         }
    end

    rule optional_frac
        frac_number? {
            def value
                [:optional_frac, text_value]
            end
        }
   end



   rule frac_number
        (s? regular_number '/' regular_number)? / ('/' regular_number)?  {
            def value
                [:frac_number, text_value]
            end
        }
   end


   rule regular_number
        [0-9\.\/-]+ {
            def value
                text_value
            end 
        }

   end

end

When I try to get the values from

2 => number
1/2 => number, frac_number
2 2/4 => not recognized

I though the rule

s? regular_number '/' regular_number

would return as a fraction. any idea what is wrong in my grammar?

Was it helpful?

Solution

I finally got this working, not ideal, but I am able to recognize the fractions properly.

    rule number 
     frac_number / regular_number optional_frac {
            def value
                [:number, text_value]
            end
        }
   end



   rule optional_frac
        frac_number? {
            def value
                [:optional_frac, text_value]
            end
        }
   end



   rule frac_number
        (s? regular_number '/' regular_number)  {
            def value
                [:frac_number, text_value]
            end
        }
   end

This takes care of the following cases (1/2, 1, 1 1/2). Then, when I have my tree, I'll have to test for the make-up of 'number', and if it has a fraction, I'll eval the fraction to get a decimal, and add it to the number if their is one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top