Evan Martin (evan) wrote in evan_tech,
Evan Martin
evan
evan_tech

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
Subscribe

  • your vcs sucks

    I've been hacking on some Haskell stuff lately that's all managed in darcs and it's reminded me of an observation I made over two years ago now (see…

  • ghc llvm

    I read this thesis on an LLVM backend for GHC, primarily because I was curious to learn more about GHC internals. The thesis serves well as an…

  • found my bug!

    Not too interesting, but this has been bugging me for a week. Been working on a toy program that proxies a TCP connection. It was working fine for…

  • Post a new comment

    Error

    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.
  • 3 comments