First go with Parsec

June 19, 2007

Parsec is a library I’ve been interested in trying out seriously since I discovered it. I have written basic parsers for Java projects before and it has not been fun. The Parsec examples I’ve seen have captured my interest. So, now that I’ve decided I’d like to start a decent sized Haskell project I looked for something where Parsec would be involved.

This post describes the result of my first attempts at using the Parsec library for something semi serious. It’s not intended as a tutorial or introduction to Parsec, but to show how simple and straight forward it can be to use.

The Project

I decided to have a go at developing a SmallTalk interpreter. SmallTalk is a language that I have heard a lot about, but never really had a chance to invest the time in ‘getting’ the built in GUI approach, so I thought developing a program that can read SmallTalk from a text file and run it might be fun (similar to GST, I think). I will refer to this project as HST – Haskell SmallTalk.

Of course, I attempt this with no knowledge of compilers/interpreters since my university days (and a fair bit of that knowledge has disappeared).

First Steps

I decided to start with, what I guess is, best described as a Spike Solution. The famous ‘Hello World’ is a good candidate for this. The code is as follows


Transcript show: 'hello world'

Looking through the draft ANSI standard for SmallTalk provides me with the following EBNF for parsing the above:


<smalltalk program> ::= <program element>
<program element> ::= <program initializer definition>
<program initializer definition> ::= <initializer definition>
<initializer definition> ::= <statements>
<statements> ::= <expression>
<expression> ::= <basic expression>
<basic expression> ::= <primary> <messages>
<messages> ::= <keyword message>
<keyword message> ::= keyword <keyword argument>
<keyword argument> ::= <primary>
<primary> ::= identifier | <literal>
<literal> ::= <string literal>
<string literal> ::= quotedString

To get started, I’ll just concern myself with those parts from <basic expression> down.

Next, I’d like to look at what Haskell data structures I’d like to parse this into.


newtype Identifier = Identifier String
newtype Literal = StringLiteral String
data Primary = PrimaryLiteral Literal | PrimaryIdentifier Identifier
newtype Keyword = Keyword String
data Message = KeywordMessage Keyword Primary
data BasicExpression = BasicExpression Primary Message

I think this will work. So, the resulting data structure after parsing ‘Hello World’ should be:


BasicExpression
  (PrimaryIdentifier (Identifier "Transcript"))
  (KeywordMessage
    (Keyword "show")
    (PrimaryLiteral (StringLiteral "Hello World")))

Onto Parsec

Lets start at the bottom. First look at <string literal>. String literals in SmallTalk are surrounded by single quotes. The parsec function names are quite descriptive and allow me to pretty much translate the syntax descriptions.


stringLiteral = do
    (char '\\'')
    s <- manyTill anyChar (char '\\'')
    return $ StringLiteral s

Tesing in ghci


*HST.Parse> parseTest stringLiteral "'HelloWorld'"
StringLiteral "Hello World"

Seems to work.

Keywords and Identifiers are similar.


keyword = do
    k <- manyTill letter (char ':')
    return $ Keyword k

identifier = do
    i <- many1 letter
    return $ Identifier i

Next we move on to some more interesting stuff. <primary> gets a little tricky, as it requires us to attempt parsing either a string literal or an identifer. As both these parsers return different types it’s not possible to combine them directly using the <|> operator. The below works for me, but I’m not sure this is the best way to approach it.


primary = do {
        i <- identifier;
        return $ PrimaryIdentifier i; }
    <|>   do {
        l <- stringLiteral;
        return $ PrimaryLiteral l; }

<keyword message> is more straight forward, but it’s here that we start having to be careful with whitespace. The code that works for me is:


keywordMessage = do
    k <- keyword
    spaces
    p <- primary
    return $ KeywordMessage k p

and finally, we get to <basic expression>. Again, this is straight forward, just as long as we are careful with whitespace.


basicExpression = do
    p <- primary
    spaces
    m <- keywordMessage
    return $ BasicExpression p m

Finally, testing with ghci


*HST.Parse> parseTest basicExpression "Transcript show: 'Hello World'"
BasicExpression
  (PrimaryIdentifier (Identifier "Transcript"))
  (KeywordMessage (Keyword "show") (PrimaryLiteral (StringLiteral "Hello World")))

Bingo.

Closing

The result is not perfect or robust, and probably not even efficient, but this will come later. The parsing code for ‘Hello World’ has come together quickly and allows for further development of the spike.

51 Responses to “First go with Parsec”


  1. […] 22nd, 2007 To start gaining experience with Parsec and Haskell I completed the first working version of a parser for SmallTalk’s version of ‘Hello World’. To follow up I decided it […]


  2. This is Smalltalk, not SmallTalk ! Have fun.

  3. lstephen Says:

    Ah yes, so it is. Not sure where I got that capitalization from. I’ll make sure to get it right in the future 🙂


  4. […] on the Spike Solution for HST – a simple Smalltalk interpreter developed in Haskell. In my previous two posts, I developed a parser that was able to parse a Smalltalk version of ‘Hello […]

  5. Mspoiidz Says:

    I’m training to be an engineer http://qaienuqe.de.tl nymphette fuck I’m with Kellie on this…only I’m not married. If i could find a nice black cock to thrust into my I’d be soooo happy

  6. Tvhkqmbw Says:

    Is there ? http://paeimoanek.de.tl preteen bbs little even tho this is extreme porn and nasty it still makes ur dick hard n pussy wet, all kelly wells is doin is what other girls fantasise about but never do (ok maybe the hotdog n strawberries is a lil far) but theres plenty of u girls n guys who have watched this n came over it i know i did

  7. Tsjwmkpa Says:

    How much is a Second Class stamp?

  8. Vhsixrnh Says:

    Wonderfull great site

  9. Doysshap Says:

    Have you got a telephone directory?

  10. Zoe Says:

    Stolen credit card http://levitra-20mg-reviews-ege.webspawner.com/ take levitra best results re-dispensed under any circumstances: Any pharmaceutical item that has already previously been dispensed and for which a

  11. Brooke Says:

    Insufficient funds

  12. Grace Says:

    I’m sorry, he’s

  13. Bwehuunh Says:

    What do you want to do when you\’ve finished? lolita fantasy stories sister Hate to double post but fuck.. I can\’t get over how much I love it when women grind like that… No contest if a girl wants to get me off.

  14. Ycsodwcg Says:

    I\’ve got a part-time job lolitas bbs links gallery nina can lick my ass and pound my pussy with that strap on any day of the week….damn…got my pussy drippin…

  15. Lznybzyy Says:

    Could you send me an application form? up skirt russian lolitas she may not have the tightest pussy, but when she spreads her legs, wow… so beautiful. love her big pussy lips.

  16. Brandon Says:

    I’d like to speak to someone about a mortgage http://www.embatech.com clomipramine cheap Menu Course: Side Dishes

  17. Samuel Says:

    I’ll put him on what is strattera secured before credit will be given for any exception.

  18. Kyle Says:

    How much is a Second Class stamp? http://arishort.com cost tamoxifen treatment category A VIP or A V 30 %, category A 25 %, category B 20 %, category C 15 % and category D

  19. James Says:

    this is be cool 8) http://www.filmscoring.info accutane cream transaction with an entry in the Eligibility Clarification Code (309-C9) field on the Insurance

  20. Uqhczhrw Says:

    I’m in a band http://lsmagazinexl.spazioblog.it beutiful lolitas naked art That’s quite a pretty girl in my opinion. She looks a bit like the girl next door and that’s always hot

  21. Txpwbgcn Says:

    Wonderfull great site http://innocentmodels.canalblog.com lolita spelled in russian p e o p l e . . . a d d m e a s a f r i e n d . . . i m n e w a t t h i s p a g e .. : D

  22. Hannah Says:

    Where do you live? kds lolita porn videos Great fuckin video, I would lick her asshole clean

  23. Mptpwbcu Says:

    It’s a bad line http://xnxx.0zed.com/ xnxx
    Look…she’s hot as hell!! However, she walks like a friggin’ linebacker for the Lions!!! She just needs some glamour lessons or something. Maybe a few weeks hanging out with some models she might learn how to walk.

  24. Madelyn Says:

    What qualifications have you got? price of abilify 5mg a. Have developed an innovative practice site

  25. Sophie Says:

    Directory enquiries ventolin mdi hfa priority was given to HIV-infected pregnant women and their families. Currently,

  26. Kaitlyn Says:

    We were at school together

  27. Julia Says:

    How many weeks’ holiday a year are there? http://connect.masslive.com/user/arariisal/index.html loli under nude photo God i see them all the time.. just some random dude walking round forests with there dick hanging out… lol?

  28. Trinity Says:

    Thanks for calling http://partitolotteria.org/chi-siamo/ amitriptyline buy line Presented an in-service education topic to

  29. Bob Says:

    Three years naughtyamerica
    OMG. One of my favourite pornstars doing these things with such crapy guy. OK, I forgive you, hopefully he bought you a tropic island somewhere in pacific ocean at least.

  30. Hayden Says:

    Do you play any instruments? localamateursextube
    this makes me wet

  31. kidmart промокоды Says:

    I’m interested in промо код kidmart

  32. связной промо код Says:

    A company car промокоды связной

  33. промокод domalina Says:

    I like watching football промокод domalina

  34. промокод эльдорадо Says:

    I’m retired эльдорадо промокод

  35. промокод эллос Says:

    Will I have to work shifts? эллос промокод

  36. ламода промо код Says:

    How many are there in a book? ламода промокод

  37. сотмаркет промокод Says:

    Yes, I love it! промокод сотмаркет

  38. Rachel Says:

    Could I have , please? http://www.redplanetmusic.ch/accueil/ where to buy diflucan in canada skills, including investigation, Medication used with

  39. Aaliyah Says:

    Could you send me an application form? sms spy palm This is my favorite video on this whole site.

  40. Kayla Says:

    Could you give me some smaller notes? spy software
    With the support of the AHEC Program, the Professional Experience Program has grown

  41. Jesus Says:

    What do you like doing in your spare time? youjizz
    shes hot… everytime i hear this camera man with the stuffy nose i laugh… he always says the chick has the worlds best ass or tits.. hes a liar

  42. Sofia Says:

    Do you know the address? spyware for android free download from Wolters Kluwer Health, Inc. Accessed [date].

  43. Zachary Says:

    What company are you calling from? http://redtube.xmov8.com/ redtube
    she can’t suck a dick for her life! she only stuck her tongue out and barely brushed it against the cock! and those are so small it wouldn’t have been to hard to get to go ball deep!

  44. Emily Says:

    I’ve lost my bank card http://xvideo.xmov8.com/ xvideo
    wow, never noticed that asian guy. at the end he shoulda came out yelling kamikaze and jizzed on her haha

  45. Matthew Says:

    Very interesting tale thirteen year old girl porn site JERRY SPRINGER GIRL HAHAHHAAH SHE MADE IT GOOD!

  46. Amia Says:

    The United States

  47. Jenna Says:

    Looking for a job signs my wife is cheating again ” Prescription/medication Reference Number


Leave a reply to Kyle Cancel reply