Haskell - 如何最好地表示一个编程语言的语法? [英] Haskell - How to best to represent a programming language's grammar?
问题描述
我无法完全理解的是如何用Haskell-ian方式表示语言的语法。我的第一个想法是使用递归数据类型定义,但我不能看到我如何使用它们来匹配语言中的关键字(if)。
想法和建议非常感谢,
Pete
数据类型就可以了。例如,给定语言:
expr :: = var
| true
| false
| ifexprthenexprelseexpr
| (expr)
此语言的示例表达式为:
if true then x else(if false then y else true)
您的Haskell数据类型如下所示:
data Expr = Var String
| Lit Bool
|如果Expr Expr Expr
您的解析器会小心翻译,例如 x
into Varx
和 true
into
等。Ie:
parseif x then false else true
= = If(Varx)(Lit False)(Lit True)
使用Norman的回答中提到的技术,或使用 Parsec 或使用解析器生成器,如快乐。
I've been looking at Haskell and I'd quite like to write a compiler (as a learning exercise) in it, since a lot of it's innate features can be readily applied to a compiler (particularly a recursive decent compiler).
What I can't quite get my head around is how to represent a language's grammar in a Haskell-ian way. My first thought was to use recursive data type definitions, but I can't see how I use them to match against keywords in the language ("if") for example.
Thoughts and suggestions greatly appreciated,
Pete
A recursive data type is fine for this. For example, given the language:
expr ::= var
| "true"
| "false"
| "if" expr "then" expr "else" expr
| "(" expr ")"
an example expression in this language would be:
if true then x else (if false then y else true)
Your Haskell data type would look something like this:
data Expr = Var String
| Lit Bool
| If Expr Expr Expr
Your parser then takes care to translate, e.g., x
into Var "x"
, and true
into Lit True
, etc. I.e.:
parse "if x then false else true"
== If (Var "x") (Lit False) (Lit True)
For writing parsers you can roll your own using the techniques mentioned in Norman's answer, or using Parsec or use parser generators like Happy.
这篇关于Haskell - 如何最好地表示一个编程语言的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!