Jan. 24th, 2017

xacid: (Default)
import org.parboiled2._

object Tagless extends scala.App {

  trait Term[T] {
    def ref(n: String): T
    def lam(n: String, t: T): T
    def app(f: T, a: T): T
  }

  trait Expr[T] {
    def oper(a: T, f: String, b: T): T
    def parens(a: T): T
  }

  trait Literal[T] {
    def int(i: Int): T
  }

Read more... )
  type Id[A] = A

  trait ~>[F[_], G[_]] {
    def apply[A](fa: F[A]): G[A]
  }

  trait FTerm[F[_]] extends Term[F ~> Id] {
    def alg[A](f: F[A]): Term[A]
    def ref(n: String) =
      Lambda[F ~> Id](alg(_).ref(n))
    def lam(n: String, t: F ~> Id) =
      Lambda[F ~> Id](x => alg(x).lam(n, t(x)))
    def app(f: F ~> Id, a: F ~> Id) =
      Lambda[F ~> Id](x => alg(x).app(f(x), a(x)))
  }

  trait FExpr[F[_]] extends Expr[F ~> Id] {
    def alg[A](f: F[A]): Expr[A]
    def oper(a: ~>[F, Id], f: String, b: ~>[F, Id]) =
      Lambda[F ~> Id](x => alg(x).oper(a(x), f, b(x)))
    def parens(a: ~>[F, Id]): ~>[F, Id] =
      Lambda[F ~> Id](x => alg(x).parens(a(x)))
  }

  trait FLiteral[F[_]] extends Literal[F ~> Id] {
    def alg[A](f: F[A]): Literal[A]
    def int(i: Int) = Lambda[F ~> Id](alg(_).int(i))
  }

  trait FSym extends FTerm[Sym]
    with FExpr[Sym] with FLiteral[Sym] {
    def alg[A](f: Sym[A]): Sym[A] = f
  }

  type SymAst = Sym ~> Id

  case class FSymParser(input: ParserInput)
    extends Parser with FSym with SymParser[SymAst]
Read more... )
  val main = "(x -> y -> z -> y * ( y * z + x))"
  val answer = parser(main)

  println(answer.map(ShowSym(_)))
  println(answer.map(SymVM(_, 1, 2, 10)))

  println(parser(main + " 1 2 10").map(x =>
    ShowSym(x) + " = " + SymVM(x)))

}

Profile

xacid: (Default)
xacid

June 2017

S M T W T F S
    123
45678910
11121314151617
18192021222324
252627282930 

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 23rd, 2017 10:55 am
Powered by Dreamwidth Studios