2

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?

Jon Purdy
  • 53,300
  • 8
  • 96
  • 166
sinoTrinity
  • 1,125
  • 2
  • 15
  • 27

1 Answers1

1

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.

amalloy
  • 89,153
  • 8
  • 140
  • 205