Take the 2-minute tour ×

It's possible to use the Scheme primitive read, which consumes a stream of characters and outputs an s-expression (sexpr).

I'm trying to write a parser in Haskell. What is the equivalent of the above? How would I implement it so that, if passed "{+ {- 3 4} 7}" it returns (list '+ (list '- 3 4) 7) (or the equivalent)?

Thanks in advance.

share|improve this question
You can find this helpful: stackoverflow.com/questions/6429047/… –  bravit Sep 28 '11 at 3:43

2 Answers 2

I think one of the first questions all those new to haskell should ask when they want to know "Can I do something?" is "What should the types be?". If you wanted to do what you're after, then I would suggest writing an AST like so:

data AST = Num Int
         | Add AST AST
         | Sub AST AST
         | Mul AST AST

Then you could write a parser of potentially with the type:

parseAST :: String -> AST

To actually write this parser, you'll probably want to use something like parsec, though if the grammar is how you've described, then you could probably write your own parsed by hand that would work quite well (and help you learn).

From there, you can write functions that can evaluate the AST, or manipulate it however you like. But it is important to realise that you can't* create new code at runtime, because that's very likely to not be type safe, or safe at all.

* I'm sure there are ways to do this, but I felt that it was more important to foster the ideas that a beginning haskell programmer should learn before moving onto more advanced topics.

share|improve this answer

You'd be better off using a proper parsing library like uu-parsinglib, polyparse or parsec.

You can abuse Read to parse an arbitrary String into some data representation (which you'll have to define).

share|improve this answer
Okay, so how would I go about implementing the second option? I can't find any documentation (that I can understand) on Read... So I just don't know how to use it. Thanks! –  user686605 Sep 28 '11 at 17:50
@chrislegend: By "second option" you mean "abuse Read"? I recommend against it, for the reasons I describe here. Otherwise, construct a data-type like Axman6 started describing in his answer and then write an appropriate parser, see for example RWH where they define a JSON type and then parse it. –  ivanm Sep 28 '11 at 22:36

Your Answer

