Last active
July 17, 2017 14:11
-
-
Save Rydgel/6b094629845f3e5af6a6ec3a0ec0be99 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cats.free.Free | |
import cats.free.Free.liftF | |
import cats.~> | |
import cats.effect.IO | |
object Brainfuck { | |
type Program[A] = Free[Brainfuck, A] | |
sealed trait Brainfuck[A] | |
case object IncPtr extends Brainfuck[Unit] | |
case object DecPtr extends Brainfuck[Unit] | |
case object IncByte extends Brainfuck[Unit] | |
case object DecByte extends Brainfuck[Unit] | |
case object ByteOut extends Brainfuck[Unit] | |
case object ByteIn extends Brainfuck[Unit] | |
case class Loop(body: Program[Unit]) extends Brainfuck[Unit] | |
def incrPtr(): Program[Unit] = | |
liftF(IncPtr) | |
def decPtr(): Program[Unit] = | |
liftF(DecPtr) | |
def incByte(): Program[Unit] = | |
liftF(IncByte) | |
def decByte(): Program[Unit] = | |
liftF(DecByte) | |
def byteOut(): Program[Unit] = | |
liftF(ByteOut) | |
def byteIn(): Program[Unit] = | |
liftF(ByteIn) | |
def loop(body: Program[Unit]): Program[Unit] = | |
liftF(Loop(body)) | |
def mySampleProgram: Program[Unit] = { | |
for { | |
_ <- incrPtr() | |
_ <- incrPtr() | |
_ <- byteOut() | |
} yield () | |
} | |
val helloworld = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." | |
def impureCompiler: Brainfuck ~> IO = | |
new (Brainfuck ~> IO) { | |
def apply[A](fa: Brainfuck[A]): IO[A] = | |
fa match { | |
case IncPtr => | |
IO { | |
println(" inc") | |
} | |
case DecPtr => | |
IO { | |
println("dec") | |
} | |
case IncByte => IO { | |
} | |
case DecByte => IO { | |
} | |
case ByteOut => | |
IO { | |
println(" byteout") | |
} | |
case ByteIn => IO { | |
} | |
case Loop(l) => IO { | |
} | |
} | |
} | |
} | |
object Main { | |
def main(args: Array[String]): Unit = { | |
import Brainfuck._ | |
val myIO = mySampleProgram.foldMap(impureCompiler) | |
myIO.unsafeRunSync() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment