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

  • 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…

  • inspiration

    _why: "when you don't create things, you become defined by your tastes rather than ability. your tastes only narrow & exclude people. so create."

  • perl people, explain your language to me

    Every time I use perl I feel mildly positive about it right up until I encounter CPAN. I've never managed to make CPAN work, despite the multitude of…

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