Parsing a binary tree structure

Hey there! I am currently making a binary tree parser for elm with the following structure:
“[1,2,3]” becomes Node 2 1 3, indicating that the middle node gets swapped with the one on its left.
So far, this is what I’ve got:

module BinaryParser exposing (..)
import Debug exposing (..)
import Html exposing (Html)
import Parser exposing (..)
import Set exposing (..)

type Tree
    = Nil
    | Node Int Tree Tree
 
swapElement : Tree -> Int -> Tree -> Tree
swapElement left val right = 
    Node val left right

treeParser : Parser Tree
treeParser =
  oneOf
    [
    succeed swapElement
        |. symbol "["
        |= lazy (\_ -> treeParser)
        |. symbol ","
        |= int
        |. symbol ","
        |= lazy (\_ -> treeParser)
        |. symbol "]"
    ]

userInputParser : Parser Tree
userInputParser =
    succeed identity
        |= treeParser
        |. end
        
binary = Parser.run userInputParser "[1,9,3]"

my_results: List String
my_results =
    [
        pr <| binary
    ] 
    

The problem I have is quite confusing: it outputs the following:
Err [{ col = 2, problem = ExpectingSymbol “[”, row = 1 }]
This seems a bit odd to me as I have the ‘[’ symbol.
Any advice/ideas would be appreciated!

You do have the first [ but then your parser recursively calls itself (as the only option), so it tries to find another [. (Hence the error on column 2.) I think you need to add a case for the Nil branch to the oneOf call in treeParser.

I too think you just need to add succeed Nil:

treeParser : Parser Tree
treeParser =
  oneOf
    [ succeed swapElement
        |. symbol "["
        |= lazy (\_ -> treeParser)
        |. symbol ","
        |= int
        |. symbol ","
        |= lazy (\_ -> treeParser)
        |. symbol "]"
    , succeed Nil
    ]

Disclaimer: I’ve not used the Elm parser library before but I’ve used plenty other parser-combinator libraries and from what I read this one is heavily influenced by parsec and co.
But I’ve had only a quick look at the document concerning backtracking and maybe you’ll have to add one here.
I don’t think so because as you look for the opening [ there should’ve been no tokens consumed if it fails at this point and if it get past [ you should be in the case where you need to see a complete Node or it’s an error - so you should be fine.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.