Haskell - 如何最好地表示一个编程语言的语法? [英] Haskell - How to best to represent a programming language's grammar?

查看:149
本文介绍了Haskell - 如何最好地表示一个编程语言的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找Haskell,我很想写一个编译器(作为一个学习练习),因为它的许多内在的功能可以很容易地应用于编译器(特别是递归的良好的编译器) 。



我无法完全理解的是如何用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆