Skip to content

Instantly share code, notes, and snippets.

@edadma
edadma / Pow.scala
Created April 4, 2020 03:58
Tail recursive exponentiation by squaring
def pow(x: Int, n: Int) = {
def pow(y: Int, x: Int, n: Int): Int =
n match {
case 0 => 1
case 1 => x * y
case _ if n % 2 == 0 => pow(y, x * x, n / 2)
case _ => pow(x * y, x * x, (n - 1) / 2)
}
if (n < 0) sys.error(s"pow: negative exponent: $n") else pow(1, x, n)
@edadma
edadma / PrecedenceClimingParsingExample.scala
Last active April 3, 2020 23:23
Precedence Climing parsing algorithm example
object Main extends App {
val symbols =
Map[String, (PrefixOperator, InfixOperator)](
"+" -> (PrefixOperator(30, +_), InfixOperator(10, LeftAssoc, _ + _)),
"-" -> (PrefixOperator(30, -_), InfixOperator(10, LeftAssoc, _ - _)),
"*" -> (null, InfixOperator(20, LeftAssoc, _ * _)),
"/" -> (null, InfixOperator(20, LeftAssoc, _ / _)),
"^" -> (null, InfixOperator(30, RightAssoc, pow)),
"(" -> null,
@edadma
edadma / dump.scala
Last active July 4, 2018 19:07
binary file dump
def dump {
val cur = file.getFilePointer
val width = 16
file.seek( 0 )
def printByte( b: Int ) = print( "%02x ".format(b&0xFF).toUpperCase )
def printChar( c: Int ) = print( if (' ' <= c && c <= '~') c.asInstanceOf[Char] else '.' )