Skip to content

Instantly share code, notes, and snippets.

@armanbilge
Created September 15, 2016 08:26
Show Gist options
  • Save armanbilge/653cbe379b2130f3ca472663e4c0c577 to your computer and use it in GitHub Desktop.
Save armanbilge/653cbe379b2130f3ca472663e4c0c577 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in scala
package bf
import java.util.Scanner
import scala.annotation.tailrec
object Main extends App {
@tailrec
def f(p: List[Char], i: Int = 0, c: Vector[Int] = Vector.fill(10000)(0), st: List[List[Char]] = Nil, ex: List[Boolean] = List(true)): Unit = if (ex.head) p match { case Nil => case '+' :: pp => f(pp, i, c.updated(i, c(i) + 1), st, ex) case '-' :: pp => f(pp, i, c.updated(i, c(i) - 1), st, ex) case '>' :: pp => f(pp, i + 1, c, st, ex) case '<' :: pp => f(pp, i - 1, c, st, ex) case '.' :: pp => print(c(i).asInstanceOf[Char]); f(pp, i, c, st, ex) case ',' :: pp => f(pp, i, c.updated(i, new Scanner(System.in).nextByte().asInstanceOf[Int]), st, ex) case '[' :: pp => f(pp, i, c, p :: st, (c(i) != 0) :: ex) case ']' :: pp => f(st.head, i, c, st.tail, ex.tail) case _ :: pp => f(pp, i, c, st, ex) } else p match { case Nil => case '[' :: pp => f(pp, i, c, p :: st, false :: ex) case ']' :: pp => f(pp, i, c, st.tail, ex.tail) case _ :: pp => f(pp, i, c, st, ex) }
f(new Scanner(System.in).nextLine().toCharArray.toList)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment