开发者

parsing fractions in treetop

开发者 https://www.devze.com 2023-03-27 15:03 出处:网络
I\'m having a bit of difficulty parsing fractions in my treetop grammar. My grammar looks like this grammar Numbers

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 '/' re开发者_StackOverflowgular_number

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号