Re: Recursive Decent Parser (example)

new topic     » goto parent     » topic index » view thread      » older message » newer message

FWIW. I replaced main() in both Phix and Euphoria code with:

function main() 
    sequence tests = { 
        {"2 + 3 * ( 4 + 5 )", "29.000000"}, 
        {"2 + 3 * 4", "14.000000"}, 
        {"2 * 3 + 4 * 6", "30.000000"}, 
        {"2 + 2 ^ 3", "10.000000"}, 
        {"4 ^ 3", "64.000000"}, 
        {"( 2 + 2 ) ^ 3", "64.000000"}, 
        {"1 + 2 + 4" , "7.000000"}, 
        {"1 + 2 - 4" , "-1.000000"}, 
        {"4 ^ 2 ^ 2", "256.000000"}, 
        {"2 * 3 ^ 2", "18.000000"}, 
        {"( 2 + 3 ) * ( 4 + 5 )", "45.000000"}, 
        {"( 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 ) * - 1", "-3.000122"}, 
        {"( 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 )", "3.000122"}, 
        {"- 2 ^ 2", "-4.000000"}, 
        {"- 3 + ( 4 * 2 ) ^ ( 1 + 1 ) / 8 - - 1", "6.000000"} 
    } 
     
    sequence results = {} 
     
    integer i = 1 
    while i < (length(tests) + 1) do 
        --The simplest tokenizer I know of. 
        expression = split(tests[i][1], " ") 
        ptr = 1 
        sequence result = sprintf("%f", {opAddSub()}) 
        sequence pass_fail = "PASS" 
        if not equal(tests[i][2], result) then 
            pass_fail = "FAIL" 
        end if 
        results = append(results, sprintf("%s: Test: [%s] Expected: [%s] Got: [%s]\n", {pass_fail, tests[i][1], tests[i][2], result})) 
        i += 1 
    end while 
     
    i = 1 
    while i < length(results) + 1 do 
        puts(1, results[i]) 
        i += 1 
    end while 
     
    return 0 
end function 

And this is the result: (Answers limited to 6 decimal places and verified by google)

PASS: Test: [2 + 3 * ( 4 + 5 )] Expected: [29.000000] Got: [29.000000] 
PASS: Test: [2 + 3 * 4] Expected: [14.000000] Got: [14.000000] 
PASS: Test: [2 * 3 + 4 * 6] Expected: [30.000000] Got: [30.000000] 
PASS: Test: [2 + 2 ^ 3] Expected: [10.000000] Got: [10.000000] 
PASS: Test: [4 ^ 3] Expected: [64.000000] Got: [64.000000] 
PASS: Test: [( 2 + 2 ) ^ 3] Expected: [64.000000] Got: [64.000000] 
PASS: Test: [1 + 2 + 4] Expected: [7.000000] Got: [7.000000] 
PASS: Test: [1 + 2 - 4] Expected: [-1.000000] Got: [-1.000000] 
PASS: Test: [4 ^ 2 ^ 2] Expected: [256.000000] Got: [256.000000] 
PASS: Test: [2 * 3 ^ 2] Expected: [18.000000] Got: [18.000000] 
PASS: Test: [( 2 + 3 ) * ( 4 + 5 )] Expected: [45.000000] Got: [45.000000] 
PASS: Test: [( 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 ) * - 1] Expected: [-3.000122] Got: [-3.000122] 
PASS: Test: [( 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 )] Expected: [3.000122] Got: [3.000122] 
PASS: Test: [- 2 ^ 2] Expected: [-4.000000] Got: [-4.000000] 
PASS: Test: [- 3 + ( 4 * 2 ) ^ ( 1 + 1 ) / 8 - - 1] Expected: [6.000000] Got: [6.000000] 
main exited with 0.000000 
 

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu