scheme解释器 C语言实现,使用Scala写了个简单的Scheme解释器
大家好,我使用scala實現了個簡單的解釋器,能夠實現整數的加減乘除。我是照著快學 19章的 3 - 4 * 5 這個例子做的。思路也是按照它的來的。
大概是這樣 1)首先定義 factor是整數
2)那么 term : (+ factorfactor...) 就是一個完整的表達式了
3)?? 那么 expr : (+? term factor...) 等就是 嵌套的表達式代碼如下:
import scala.util.parsing.combinator._
class ExprParser extends RegexParsers {
val number = "[0-9]+".r
val op = "+" | "-" | "*" | "/"
def expr :Parser[Int] = "(" ~ opt(op) ~ rep(term | factor) ~ ")" ^^ {
case _ ~ _ ~ List() ~ _ => 0
case _ ~ Some("+") ~ r ~ _ => r.reduce(_+_)
case _ ~ Some("-") ~ r ~ _ => r.reduce(_-_)
case _ ~ Some("*") ~ r ~ _ => r.reduce(_*_)
case _ ~ Some("/") ~ r ~ _ => r.reduce(_/_)
}
def term :Parser[Int] = "(" ~ opt(op) ~ rep(factor) ~ ")" ^^ {
case _ ~ Some("+") ~ r ~ _ => r.reduce(_+_)
case _ ~ Some("-") ~ r ~ _ => r.reduce(_-_)
case _ ~ Some("*") ~ r ~ _ => r.reduce(_*_)
case _ ~ Some("/") ~ r ~ _ => r.reduce(_/_)
}
def factor:Parser[Int] = number ^^ {_.toInt}
}
object Scheme extends App
{
val parser = new ExprParser
def process():Unit = {
val read = readLine(">>>")
read match {
case "exit" => ()
case _ =>
val result = parser.parseAll(parser.expr, read)
if (result.successful)
println(result.get)
process()
}
}
println("enter exit to break")
process()
} 程序運行效果如下圖:
頗有成就感 ,而且我認為我這個例子比3-4*5更好玩一些。
雖然這只是一個簡單的練習,但是感覺如果我能力上去的話,是不是就能寫個功能完備的解釋器了
哈哈,期待....
總結
以上是生活随笔為你收集整理的scheme解释器 C语言实现,使用Scala写了个简单的Scheme解释器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vb.net 教程 6-1 进程 Pro
- 下一篇: 常用术语中英简繁对照- -