Skip to content

Instantly share code, notes, and snippets.

import scala.util.parsing.combinator.RegexParsers
sealed trait Command
case object FlushCommand extends Command
case class LookupKey(key: String) extends Command
case class SetKey(key: String, blob: String) extends Command
object Grammar extends RegexParsers {
val id: Parser[String] = """[a-zA-Z][a-zA-Z0-9]*""".r
package sandbox;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
scala> def yearlyImprove(dailyImprove: Double): Double =
| Seq.fill(365)(1 + dailyImprove).product - 1
yearlyImprove: (dailyImprove: Double)Double
scala> yearlyImprove(0.001)
res0: Double = 0.44025131342952095
@sortega
sortega / LineCount.scala
Created September 3, 2015 17:02
Line count kata
package lines
import java.io.File
import scala.annotation.tailrec
object LineCount {
def of(file: File): Int = {
val source = scala.io.Source.fromFile(file)
try of(source.toStream)
@sortega
sortega / Distro.scala
Created August 18, 2015 21:40
Another incarnation of the discrete probability monad
package distro
import scala.annotation.tailrec
import scala.util.Random
trait Distro[A] {
def eventSet: Set[A]
def probOf(event: A): BigDecimal
def map[B](f: A => B): Distro[B]
def flatMap[B](f: A => Distro[B]): Distro[B]
@sortega
sortega / Sieve.scala
Created August 14, 2015 16:09
Sequential Eratosthenes sieve
class Sieve(maxNumber: Int) {
private val candidates = Array.fill(maxNumber + 1)(true)
def run(): Unit = {
for (index <- 2 to maxNumber) {
if (candidates(index)) {
crossOutMultiples(index)
}
}
}
@sortega
sortega / BackPressureSieve.scala
Created August 14, 2015 16:02
Parallel Eratosthenes sieve with back pressure
import akka.actor._
object BackPressureSieve extends App {
val DefaultChunkSize = 1024
val MinChunkSize = DefaultChunkSize * 3 / 4
val MaxNumber = 500000
case object GetCandidates
case class Candidates(values: Vector[Int])
@sortega
sortega / SimpleSieve.scala
Created August 14, 2015 15:35
Naïve parallelization of the Eratosthenes sieve using Akka
import akka.actor._
object SimpleSieve extends App {
val MaxNumber = 500000
case object NoMoreCandidates
class Filter extends Actor {
@sortega
sortega / Game.scala
Last active August 29, 2015 14:26
Bowling game score. Imperative, OO style
package bowling
class Game {
trait Line {
def addRoll(pins: Int): Unit
def score: Int
}
class Frame(next: Line) extends Line {
@sortega
sortega / WithScalaz.scala
Last active August 29, 2015 14:22
Briconsejo option
import scalaz.syntax.std.boolean._
boolExpression.option(computingSomethingComplicated)