开发工具:
文件大小: 23mb
下载次数: 0
上传时间: 2012-04-17
详细说明: // Contributed by Daniel Gronau import scala.annotation._ trait Func[T] { val zero: T def inc(t: T): T def dec(t: T): T def in: T def out(t: T): Unit } object ByteFunc extends Func[Byte] { override val zero: Byte = 0 override def inc(t: Byte) = ((t + 1) & 0xFF).toByte override def dec(t: Byte) = ((t - 1) & 0xFF).toByte override def in: Byte = readByte override def out(t: Byte) { print(t.toChar) } } case class Tape[T](left: List[T], cell: T, right: List[T])(implicit func: Func[T]) { priv ate def headOf(list:List[T]) = if (list.isEmpty) func.zero else list.head private def tailOf(list:List[T]) = if (list.isEmpty) Nil else list.tail def isZero = cell == func.zero def execute(ch: Char) = (ch: @switch) match { case '+' => copy(cell = func.inc(cell)) case '-' => copy(cell = func.dec(cell)) case '<' => Tape(tailOf(left), headOf(left), cell :: right) case '>' => Tape(cell :: left, headOf(right), tailOf(right)) case '.' => func.out(cell); this case ',' => copy(cell = func.in) case '[' | ']' => this case _ => error("Unexpected token: " + ch) } } object Tape { def empty[T](func: Func[T]) = Tape(Nil, func.zero, Nil)(func) } class Brainfuck[T](func:Func[T]) { def execute(p: String) { val prog = p.replaceAll("[^\\+\\-\\[\\]\\.\\,\\>\\<]", "") @tailrec def braceMatcher(pos: Int, stack: List[Int], o2c: Map[Int, Int]): Map[Int,Int] = if(pos == prog.length) o2c else (prog(pos): @switch) match { case '[' => braceMatcher(pos + 1, pos :: stack, o2c) case ']' => braceMatcher(pos + 1, stack.tail, o2c + (stack.head -> pos)) case _ => braceMatcher(pos + 1, stack, o2c) } val open2close = braceMatcher(0, Nil, Map()) val close2open = open2close.map(_.swap) @tailrec def ex(pos:Int, tape:Tape[T]): Unit = if(pos < prog.length) ex((prog(pos): @switch) match { case '[' if tape.isZero => open2close(pos) case ']' if ! tape.isZero => close2open(pos) case _ => pos + 1 }, tape.execute(prog(pos))) println("---running---") ex(0, Tape.empty(func)) println("\n---done---") } } /* Run with: val bf = new Brainfuck(ByteFunc) bf.execute(""">+++++++++[<++++++++>-]<.>+++++++[<++ ++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] <.#>+++++++++++[<+++++>-]<.>++++++++[<++ +>-]<.+++.------.--------.[-]>++++++++[<++++> -]<+.[-]++++++++++.""") */ ...展开收缩
(系统自动生成,下载前可以参看下载内容)
下载文件列表
相关说明
- 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
- 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度。
- 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
- 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
- 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
- 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.