简体   繁体   English

在Haskell中阅读

[英]Read in Haskell

It's possible to use the Scheme primitive read, which consumes a stream of characters and outputs an s-expression (sexpr). 可以使用Scheme原语读取,该原语消耗字符流并输出s表达式(sexpr)。

I'm trying to write a parser in Haskell. 我正在尝试在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)? 我将如何实现它,以便在传递"{+ {- 3 4} 7}"后返回(list '+ (list '- 3 4) 7) (或等效值)?

Thanks in advance. 提前致谢。

You'd be better off using a proper parsing library like uu-parsinglib , polyparse or parsec . 您最好使用适当的解析库,例如uu-parsinglibpolyparseparsec

You can abuse Read to parse an arbitrary String into some data representation (which you'll have to define). 可以滥用Read将任意String解析为某种数据表示形式(必须定义)。

I think one of the first questions all those new to haskell should ask when they want to know "Can I do something?" 我认为,haskell的所有新手都应该在想知道“我能做些什么?”时提出的第一个问题。 is "What should the types be?". 是“类型应该是什么?”。 If you wanted to do what you're after, then I would suggest writing an AST like so: 如果您想做您想做的事,那么我建议像这样编写AST:

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). 要实际编写此解析器,您可能需要使用诸如parsec之类的方法,尽管如果语法是您所描述的方式,那么您可以手工编写自己的解析器,这样会很好地工作(并帮助您学习)。

From there, you can write functions that can evaluate the AST, or manipulate it however you like. 从那里,您可以编写可以评估AST的函数,也可以根据需要对其进行操作。 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. *我敢肯定,有很多方法可以做到这一点,但是我认为,培养起步的Haskell程序员在进入更高级的主题之前应该学习的思想更为重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM