Issue when parsing array[1][2] using Megaparsec

84 views Asked by At

I was following Megaparsec documentation to parse multidimensional array.

opSubscript = Postfix $ foldr1 (.) <$> some singleIndex

singleIndex = do
  index < brackets expr
  return $ \l -> ArrayIndex l index

array[1][2] is expected to be parsed as

ArrayIndex (ArrayIndex (Var "array") 1)) 2

However, it was

ArrayIndex (ArrayIndex (Var "array") 2)) 1

What is going wrong here?

1

There are 1 answers

1
amalloy On

some singleIndex has parsed a list containing two functions, [f, g], where

f = \l -> ArrayIndex l 1
g = \l -> ArrayIndex l 2

And then composed them with foldr1. And since

foldr1 f [x, y] = x `f` y

your resulting function is f . g. Naturally this applies g first, yielding ArrayIndex (Var "array") 2, and then applies f next, yielding ArrayIndex (ArrayIndex (Var "array") 2) 1.

So your parsing is fine, but you are composing the results wrong. You want a different associativity, or order or something.