Search code examples
haskells-expression

Parsing S Expression


Given the following definitions that make up an S Expression from Prof. Yorgey's course:

data Atom = N Integer | I Ident deriving Show

and

data SExpr = A Atom | Comb [SExpr] deriving Show

What should the full data type be (in Haskell) for the following?

(bar (foo) 3 5 874)


Solution

  • I believe it would be something like

    Comb
        [ A (I "bar")
        , Comb
            [ A (I "foo")
            ]
        , A (N 3)
        , A (N 5)
        , A (N 874)
        ]
    

    Whenever you encounter an open parenthesis you would start a new Comb expression, so (foo) is Comb [A (I "foo")] while foo is simply A (I "foo").