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

  • icfp results

    IFCP results. Google's Team Smartass won again. No surprise there; those guys are truly scary smart.

  • icfp conclusion

    ICFP this year: still good, but a bit of a bummer. You were given "DNA" (a 7mb string of the letters I,C,F,P) and instructions on how to parse and…

  • icfp!

    This weekend I've been working on the ICFP contest again. I'm taking much more casually than last year -- I started after dinner last night and gave…

  • 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