Read in Haskell
It's possible to use the Scheme primitive read, which cons开发者_开发问答umes 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.
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).
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
etc.
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.
精彩评论