parseElements :: Grammar Arr t1 t2 -> (Array, t1) -> Parser (Array, t2)
parseElements = \case
  Id        -> return
  g1 :. g2  -> parseElements g2 >=> parseElements g1

  Empty     -> \_ -> fail "empty grammar"
  g1 :<> g2 -> parseElements g1 <> parseElements g2

  Pure f _  -> \(arr, x) -> (arr, ) <$> f x
  Many g    -> manyM (parseElements g)

  Element g -> \(arr, x) ->
    if V.null arr
      then fail "expected at least one more array element"
      else do
        y <- parseValue g (V.last arr :- x)
        return (V.init arr, y)
parseElements :: Grammar Arr t1 t2 -> (Array, t1) -> Parser (Array, t2)
parseElements = \case
  Id        -> return
  g1 :. g2  -> parseElements g2 >=> parseElements g1

  Empty     -> \_ -> fail "empty grammar"
  g1 :<> g2 -> parseElements g1 <> parseElements g2

  Pure f _  -> \(arr, x) -> (arr, ) <$> f x
  Many g    -> manyM (parseElements g)

  Element g -> \(arr, x) ->
    if V.null arr
      then fail "expected at least one more array element"
      else do
        y <- parseValue g (V.last arr :- x)
        return (V.init arr, y)
parseElements = \case
  Id        -> return
  g1 :. g2  -> parseElements g2 >=> parseElements g1

  Empty     -> \_ -> fail "empty grammar"
  g1 :<> g2 -> parseElements g1 <> parseElements g2

  Pure f _  -> \(arr, x) -> (arr, ) <$> f x
  Many g    -> manyM (parseElements g)

  Element g -> \(arr, x) ->
    if V.null arr
      then fail "expected at least one more array element"
      else do
        y <- parseValue g (V.last arr :- x)
        return (V.init arr, y)