Skip to content

Instantly share code, notes, and snippets.

@dcsobral
Created July 11, 2012 20:19
Show Gist options
  • Save dcsobral/3093046 to your computer and use it in GitHub Desktop.
Save dcsobral/3093046 to your computer and use it in GitHub Desktop.
Scala 2.10 -- De onde viemos e para onde vamos? Snippets de código
// Try
def percentCompleted(total: Int,
done: Int): Int =
Try ( done * 100 / total ) getOrElse 100
// Try/rescue/recover/andThen
Try {
new FileInputStream(a)
} rescue {
case _: FileNotFoundException =>
new FileInputStream(b)
} recover {
case _: FileNotFoundException =>
defaultInputStream
} andThen {
stream =>
in = stream.read(); Stream.close(); in
}
// Hashing
def hashingOf[T : Hashing](obj: T): Int =
implicitly[Hashing[T]].hash(obj)
// Uma função de hashing ruim para Seqs
implicit val seqHashing =
Hashing fromFunction ((_: Seq[_]).size)
// IsTraversableOnce, IsTraversableLike
class FilterMapImpl[A, Repr]
(val r: GenTraversableLike[A, Repr]) {
final def filterMap[B, That]
(f: A => Option[B])
(implicit cbf: CanBuildFrom[Repr, B, That])
: That =
r.flatMap(f(_).toSeq)
}
implicit def filterMap[Repr, A](r: Repr)
(implicit fr: IsTraversableOnce[Repr])
: FilterMapImpl[fr.A,Repr] =
new FilterMapImpl(fr.conversion(r))
// Configuração de coleções paralelas
import scala.collection.parallel._
val pc = mutable.ParArray(1, 2, 3)
pc.tasksupport = new ForkJoinTaskSupport(
new scala.concurrent.ForkJoinPool(2))
pc map { _ + 1)
pc.tasksupport = new ThreadPoolTaskSupport()
// Custom task support
class customTaskSupport extends TaskSupport {
def execute[R, Tp]
(task: Task[R, Tp]): () => R = ???
def executeAndWaitResult[R, Tp]
(task: Task[R, Tp]): R = ???
def parallelismLevel: Int = ???
}
// String Interpolation 1
def hello(name: String = "world"): String =
"Hello, " + name + "! "
// Interpolation!
def hello(name: String = "world"): String =
s"Hello, $name! "
// String Interpolation 2
def percentCompleted(total: Int, done: Int): String =
Try ( done * 100 / total ) map {
percent => f"$percent%2d% completed"
} getOrElse "100% completed"
def percentCompleted(total: Int, done: Int): String =
Try (
f"${ done * 100 / total }%2d% completed"
) getOrElse "100% completed"
// String Interpolation -- traduções
s"Hello, $name!" // traduzido para
StringContext("Hello, ", "!").s(name)
f"${ done * 100 / total }%2d% completed" // traduzido para
StringContext("", "%2d% completed").f(done * 100 / total)
// String Context 3
// Adição de interpolação via implicit
class RegexContext(sc: StringContext) {
def r(args: Any*) = {
sc.checkLengths(args: _*)
val res = (args, sc.parts.tail).zipped map {
(arg, part) => s"\\Q$arg\\E$part"
} mkString ""
(sc.parts.head + res).r
}
}
implicit def toRC(sc: StringContext) = new RegexContext(sc)
// String Context 4
// Aninhamento de interpoladores
class RegexContext(sc: StringContext) {
def r(args: Any*) = {
sc.checkLengths(args: _*)
s"${sc.parts.head}${
(args, sc.parts.tail).zipped map {
(arg, part) => s"\\Q$arg\\E$part"
} mkString ""
}".r
}
}
implicit def toRC(sc: StringContext) = new RegexContext(sc)
// String Context 5
// Adição de interpolação via sobreposição
object StringContext(parts: String*) {
def r(args: Any*) = {
require(parts.length == args.length + 1)
val res = (args, parts.tail).zipped map {
"\\Q" + _ + "\\E" + _
} mkString ""
(parts.head + res).r }
}
// Possível alterar s e f!
// String Context 6
// apply e unapplySeq
def hello(name: String = "world"): String = i"Hello, $name!"
def who(message: String): String = message match {
case i"Hello, $name!" => name
case _ => "no clue"
}
who(hello("Daniel")) == "Daniel"
// String Context 7
// apply e unapplySeq
implicit class SI(sc: StringContext) {
object i {
def apply(args: Any*): String =
sc.parts.head +
(args,sc.parts.tail).zipped.map(_+_).mkString
def unapplySeq(s: String): Option[Seq[String]] = {
val partsr = sc.parts map (p => s"\\Q$p\\E")
val r = (partsr mkString "(.*)").r
s match { case r(xs @ _*) => Some(xs) case _ => None }
}
}
}
// String Context 8
// Adição de interpolação via implicit class
implicit class RegexContext(sc: StringContext) {
def r(args: Any*) = {
sc.checkLengths(args: _*)
val res = (args, sc.parts.tail).zipped map {
"\\Q" + _ + "\\E" + _
} mkString ""
(sc.parts.head + res).r
}
}
// Futures e Promises
// TODO – Desculpem! Exemplos da SIP:
import scala.concurrent._
val f: Future[List[String]] = future {
session.getRecentPosts
}
f onComplete {
case Right(posts) => for (post <- posts) render(post)
case Left(t) => render("An error has occured: " + t.getMessage)
}
// Futures e Promises 2
// TODO – Desculpem! Exemplos da SIP:
import scala.concurrent._
val f: Future[List[String]] = future {
session.getRecentPosts
}
f onFailure {
case t => render("An error has occured: " + t.getMessage)
} onSuccess {
case posts => for (post <- posts) render(post)
}
// Futures e Promises 3
// TODO – Desculpem! Exemplos da SIP:
import scala.concurrent._
def main(args: Array[String]) {
val rateQuote = future {
connection.getCurrentValue(USD)
}
val purchase = rateQuote map {
quote => if (isProfitable(quote)) connection.buy(amount, quote)
else throw new Exception("not profitable")
}
blocking(purchase, 0 ns)
}
// Futures e Promises 4
// TODO – Desculpem! Exemplos da SIP:
import scala.concurrent.{ future, promise }
val p = promise[T]
val f = p.future
val producer = future {
val r = produceSomething()
p success r
continueDoingSomethingUnrelated()
}
val consumer = future {
startDoingSomething()
f onSuccess {
case r => doSomethingWithResult()
}
}
// Value Classes e String Interpolation
// Adição de interpolação via implicit value class
implicit class RegexContext(sc: StringContext) extends AnyVal {
def r(args: Any*) = {
sc.checkLengths(args: _*)
val res = (args, sc.parts.tail).zipped map {
"\\Q" + _ + "\\E" + _
} mkString ""
(sc.parts.head + res).r
}
}
// Macros
object Trimmer {
def trim(s: String): String = macro trimImpl
import scala.reflect.makro.Context
def trimImpl(c: Context)(s: c.Expr[String]): c.Expr[String] = {
import c.universe._ // see reflection
val Literal(Constant(untrimmed: String)) = s.tree
val trimmed = untrimmed.lines.map(_.trim).mkString("\n")
c.Expr(Literal(Constant(trimmed)))
}
}
// Trait Dynamic
class xmlPath(xml: scala.xml.Node) extends Dynamic {
def selectDynamic(path: String) = xml \\ path
}
// scala.reflect
def intMethods[T : TypeTag](v: T) = {
val IntType = typeOf[Int]
val vType = typeOf[T]
val methods = vType.nonPrivateMembers.collect {
case m: MethodSymbol => m -> m.typeSignatureIn(vType)
}
methods collect {
case (m, mt @ NullaryMethodType(IntType)) => m -> mt
case (m, mt @ MethodType(_, IntType)) => m -> mt
case (m, mt @ PolyType(_, MethodType(_, IntType))) => m -> mt
}
}
// Mirror
val obj = "String"
val objClass = obj.getClass
val classClassLoader = objClass.getClassLoader
val classLoaderMirror = runtimeMirror(classClassLoader)
val classSymbol = classLoaderMirror.classSymbol(objClass)
val classType = classSymbol.typeSignature
val methodName = newTermName("length")
val methodSymbol = classType.member(methodName).asMethodSymbol
val instanceMirror = classLoaderMirror.reflect(obj)
val methodMirror = instanceMirror.reflectMethod(methodSymbol)
methodMirror.apply() // == (obj.length: Any)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment