Skip to content

Instantly share code, notes, and snippets.

/*
* A curried emulation of Iterable#map.
*
* map(List(1,2,3)) { _ + 2} //List[Int] = List(3, 4, 5)
*/
def map[T](l: List[T])(f: (T) => T): List[T] = {
def doMap[T](l: List[T], f: (T) => T, acc: List[T]): List[T] = l match {
case Nil => acc
case x :: tail => doMap(tail, f, acc ::: List(f(x)))
}
def combine[T](sets: List[List[T]]): List[List[T]] = sets match {
case List(l1, l2) => l1.flatMap(i1 => l2.map(List(i1, _)))
case head :: tail => combine(tail).flatMap(set => head.map(_ :: set))
case _ => sets
}
/*
* Quick sketch of wrapper to aid in raw stream processing.
* Source is nice, but it blocks in some cases (ie, client
* socket input streams). While loops suck, so ....
*
* import MIO._
* val in: InputStream = ....
* consume(in) until("\r\n\r\n")
*
* chris@thegodcode.net
/**
* A simple look at ADT-style code in place of classical objects in Scala.
*
* import ADT.Person._
* val p = create("Chris", "Lewis")
* println(firstName(p))
*/
object ADT {
class Person private (private val firstName : String, private val lastName: String)
/**
* Given a sequence of words (Array, List, etc), generate a Map[String, Int]
* of the words to how many times they appear in the sequence, filtering any
* stop words.
*/
def countWords(w: Seq[String], s: Seq[String]) =
w.filter(! s.contains(_)).foldLeft(Map[String, Int]()) { (m, w) =>
m + {
if(m.isDefinedAt(w)) w -> (m(w) + 1)
else w -> 1
/* Recursively compose an arbitrarily long list of functions into a single function. */
function compose() {
/* One function, nothing to compose. */
if(arguments.length == 1)
return arguments[0];
else {
/* Compose the head with the immediate successor. */
var args = arguments;
/* The composition: f(g(x)) */
var f = [function() {
def tryn[A <: AnyRef](f: => A) =
try {
f
} catch {
case _ => null.asInstanceOf[A]
}
// var someRef = tryn { obj.getSomethingButCauseEx }
/* Quick sketch after reading http://lssn.me/DtP.
Usage: File("a_file") << "some text"
Scala needs not the compiler's blessing for sexy. */
import java.io.{FileWriter, Writer}
/* A loaner for writers. */
trait WriterLoaner {
def write(w: Writer)(op: Writer => Unit) {
try {
@chrislewis
chrislewis / taming_either.scala
Created February 28, 2011 04:38
taming Either
class RichEither[L, R](val either: Either[L, R]) {
def mapRight[RR](f: R => RR): Either[L, RR] = either match {
case Left(l) => Left(l)
case Right(r) => Right(f(r))
}
}
implicit def either2rich[L, R](either: Either[L, R]) = new RichEither(either)
/*
class RichEither[L, R](val either: Either[L, R]) {
def map[RR](f: R => RR): Either[L, RR] = either match {
case Left(l) => Left(l)
case Right(r) => Right(f(r))
}
def flatMap[RR](f: R => Either[L, RR]): Either[L, RR] = either match {
case Left(l) => Left(l)
case Right(r) => f(r)
}