Skip to content

Instantly share code, notes, and snippets.

View bbq2100's full-sized avatar
👾

Qaiser Abbasi bbq2100

👾
View GitHub Profile
@bbq2100
bbq2100 / chapter4_10.sc
Created October 13, 2014 21:08
Scala.Either
def throwableToLeft[T](block: => T): Either[Throwable, T] = {
try {
Right(block)
}
catch {
case ex: Throwable => Left(ex)
}
}
val r = throwableToLeft {
@bbq2100
bbq2100 / chapter4_9.sc
Created October 13, 2014 20:36
PartialFunction
val languages: Seq[String] = Seq("Scala", "Haskell", "OCaml", "ML")
languages(1)
val default: PartialFunction[Int, String] = {
case _=> "Is it a FP language???"
}
val languageWithDefault = languages orElse default
languageWithDefault(15)
@bbq2100
bbq2100 / chapter4_4.sc
Created October 13, 2014 20:11
Java Collection to Traversable
import java.util
import java.util.{Collection => JCollection, ArrayList}
class JavaToTraversable[E] (javaCollection: JCollection[E]) extends Traversable[E] {
override def foreach[U](f: (E) => U): Unit = {
val iterator = javaCollection.iterator()
while(iterator.hasNext) {
f(iterator.next())
}
}
@bbq2100
bbq2100 / gist:2f88eb0c034d5c7034c3
Created October 2, 2014 20:26
Scala-Map function => pattern matching vs for-comprehension J
def mapPatternMatching[A, B](xs: List[A], f: A => B): List[B] = {
xs match {
case List() => scala.Nil
case head :: tail => f(head) :: mapPatternMatching(tail, f)
}
}
//map(List(1, 2, 3), (x: Int) => x + 1)
def mapForComprehension[A, B](xs: List[A], f: A => B) = {
@bbq2100
bbq2100 / Scala_functional
Created October 2, 2014 19:33
Scala-Options -> Type-variances, type bounds
def position[A](list: List[A], element: A) = {
val index: Int = list indexOf (element)
if (index == -1) Nil
else Just(index)
}
sealed abstract class Maybe[+A] {
def isEmpty: Boolean
def get: A
@bbq2100
bbq2100 / gist:f7045f3a7e8294a95568
Created October 2, 2014 14:38
RESTful WS with oldfashioned HTTPServlet^^
static class RestServlet extends HttpServlet {
public void addConfiguration(String key, String value) {
response.put(key, value);
}
private Map<String, String> response = new HashMap<String, String>();
public RestServlet() {
response.put("/autos", Arrays.asList("BMW", "Mercedes").toString());
@bbq2100
bbq2100 / DateTimeFormat
Created August 18, 2014 21:48
jodaTime whats up?
//-----------------------------------------------------------------------
/**
* Parses the given pattern and appends the rules to the given
* DateTimeFormatterBuilder.
*
* @param pattern pattern specification
* @throws IllegalArgumentException if the pattern is invalid
* @see #forPattern
*/
private static void parsePatternTo(DateTimeFormatterBuilder builder, String pattern) {