Evan Martin (evan) wrote in evan_tech,
Evan Martin

s-expression parser

Here's a slightly-cleaned-up version of the s-expression parser I used.
data SExp = A String | S [SExp] deriving Show

psexp = liftM S $ parens ((psexp <|> atom) `sepEndBy` spaces) where
  parens  = between (char '(') (char ')')
  atom    = liftM A (literal <|> quoted) where
    literal = many1 (lower <|> char '_')
    quoted  = do q; manyTill anyChar q where q = char '"'

No parser generator or lexer, just some function calls, and it reads almost how you'd describe parsing to another person ("a quoted string is a quote followed by a multiple characters up until a quote").

Here's a function that pretty-prints an SExp as a tree, with indents.
prettyP sexp = render (doc sexp) where
  doc (S (x:xs)) = hang (doc x) 2 $ vcat (map doc xs)
  doc (A string) = text string

The key to both of these is nice libraries.
Tags: icfp

  • blog moved

    As described elsewhere, I've quit LiveJournal. If you're interested in my continuing posts, you should look at one of these (each contains feed…

  • dremel

    They published a paper on Dremel, my favorite previously-unpublished tool from the Google toolchest. Greg Linden discusses it: "[...] it is capable…

  • treemaps

    I finally wrote up my recent adventures in treemapping, complete with nifty clickable visualizations.

  • Post a new comment


    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.