Skip to content

Instantly share code, notes, and snippets.

@halcat0x15a
Created May 17, 2013 06:43
Show Gist options
  • Save halcat0x15a/5597342 to your computer and use it in GitHub Desktop.
Save halcat0x15a/5597342 to your computer and use it in GitHub Desktop.
package bits
import scala.language.experimental.macros
import scala.reflect.macros.Context
object Macros {
def bits(n: Long) = macro impl
def impl(c: Context)(n: c.Expr[Long]): c.Tree = {
import c.universe._
def bit(n: Long): c.Tree =
if (n == 0)
reify(H).tree
else if (n % 2 == 0)
Apply(reify(O).tree, List(bit(n / 2)))
else
Apply(reify(I).tree, List(bit(n / 2)))
n match {
case Expr(Literal(Constant(x: Int))) => bit(x)
case Expr(Literal(Constant(x: Long))) => bit(x)
}
}
}
@halcat0x15a
Copy link
Author

> console
[info] Starting scala interpreter...
[info] 
Welcome to Scala version 2.11.0-20130509-143505-9e0aec0893 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> bits.Macros.bits(1)
res0: bits.I[bits.H.type] = I(H)

scala> bits.Macros.bits(0)
res1: bits.H.type = H

scala> bits.Macros.bits(1)
res2: bits.I[bits.H.type] = I(H)

scala> bits.Macros.bits(10)
res3: bits.O[bits.I[bits.O[bits.I[bits.H.type]]]] = O(I(O(I(H))))

scala> 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment