scala for rubyists

21
Scala for Rubyists Make your ideas come true by Michel Perez www.mrkaspa.com

Upload: michel-perez

Post on 12-Apr-2017

194 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Scala for rubyists

Scala for RubyistsMake your ideas come true

by Michel Perezwww.mrkaspa.com

Page 2: Scala for rubyists

Ruby :D

FELICIDAD TIPADO DINAMICO GEMS

NO IDE DOCUMENTACION FACIL DE APRENDER

Page 3: Scala for rubyists

Ruby :(

PERFORMANCE ESCALABILIDAD PROG FUNCIONAL

MANTENIBILIDAD CONCURRENCIA

Page 4: Scala for rubyists
Page 5: Scala for rubyists

I <3 Java

- JVM- Libraries- Performance- Escalabilidad- Mantenibilidad

SCALA CLOJURE

JRUBYGROOVY

Page 6: Scala for rubyists
Page 7: Scala for rubyists

PROS CONS

Primitivas de concurrencia

Desarrollado por Google

Tiempo de compilación

Lenguaje compilado

Lenguaje tipado

Sintaxis old style

Demasiado imperativo

Poco funcional

Inmutabilidad

Page 8: Scala for rubyists

PROS CONS

Primitivas de concurrencia

Erlang

Lenguaje interpretado

Funcional

Muy nuevo

Page 9: Scala for rubyists

PROS CONS

Primitivas de concurrencia

Funcional

JVM

Lenguaje interpretado

Sistema de tipado opcional

LISP

Page 10: Scala for rubyists

PROS CONS

Akka

Funcional

JVM

Tipado

Compilado

Tiempo de compilación

Curva de aprendizaje

Gestión de dependencias

Page 11: Scala for rubyists

Programacion funcionalFUNCIONES Y MAS FUNCIONES

INMUTABILIDAD

CURRYING CLOSURES

LAZY EVALUATION PATTERN MATCHING

CAMBIA LA MANERA EN COMO PROGRAMAS

Page 12: Scala for rubyists

Scala Variables?

val labels = Set(“")val labels = Set[String](“”)

var labels = Set[String](“”)

Y los tipos?

Colecciones Inmutables

Syntaxis para generics <?>

NO HAY ; :D

Que es val ?

Page 13: Scala for rubyists

Scala OOP + FP

No es la OOP el demonio?

Un buen programador de scala no usa side efect

Funciones puras

Usa OOP para abstraer datos

class Rational(x: Int, y: Int) {

def this(x: Int) = this(x, 1)

private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

private val g = gcd(x, y) def numer = x / g def denom = y / g

def < (o: Rational) = numer * o.denom < o.numer * denom

def > (o: Rational) = !(this < o)

def +(o: Rational) = { new Rational(numer * o.denom + denom * o.numer, denom * o.denom) }

def -(o: Rational) = { this + (-o) }

def unary_- = Rational(-numer, denom)

override def toString = { numer + "/" + denom }

}Cada cambio de estado genera un nuevo objeto

Page 14: Scala for rubyists

Scala OOP

Case class -> get, set, constructor auto

Traits son similares a los modulosen Ruby

Generic clases/traits

Singleton Object

case class SocialNetwork(id: String, name: String)

trait LinkedList[+A] { def isEmpty: Boolean

def head: A

def tail: LinkedList[A]

def at(index: Int): A

def prepend[B >: A](elem: B): LinkedList[B] = new Cons(elem, this)

}

object Nil extends LinkedList[Nothing] {

class Cons[A](val head: A, val tail: LinkedList[A]) extends LinkedList[A] {

Page 15: Scala for rubyists

Scala Functions

Toda funciona debe tener un tipo deretorno(type inference)

Funciones como parámetros

Retorna funciones

Vector.fill(queens.length)("* “).updated(col, "X ").mkString

def lambda = (x: Int) => x + 1

val multiplier = (i:Int) => i * 10

def sumComp(a: Int): (Int) => Int = { def sum(b: Int) = a + b}

val fun = sumComp(5)fun(1)

def sumComp(a: Int)(b: Int): Int = { a + b}

Currying

Page 16: Scala for rubyists

Pattern MatchingEs un Super Switchval secondElement = List(1,2,3) match {

case x :: y :: xs => y case _ => 0}

val foodItem = "porridge"

def goldilocks(expr: Any) = expr match { case (`foodItem`, _) => "eating" case ("chair", "Mama") => "sitting" case ("bed", "Baby") => "sleeping" case _ => "what?"}

goldilocks(("porridge", "Papa"))

Compara y extrae al mismo tiempo

Page 17: Scala for rubyists

ImplicitsParametros inyectados en un metodoo constructor de manera implicita

Sirve para realizar conversiones automaticas

implicit def implChange(str:String):Int = new Integer(str)

def sum(a:Int, b:Int):Int = a +b

sum("1", 2)

Page 18: Scala for rubyists

Monadsmap, flatMap, filter

for comprehension

def readAsync(): Future[Option[List[String]]] = Future { readFile() }

def readFile(): Option[List[String]] = Try { Source.fromURL("/tmp/file.txt").getLines().toList } toOption

val futSize: Future[Int] = for { result <- readAsync() list <- result } yield list.size

val futSizeMap: Future[Option[Int]] = readAsync().map { result: Option[List[String]] => result.map((list: List[String]) => list.size) }

Future, Option, Try, Either

Page 19: Scala for rubyists

ActorsHilos livianos

Orientados a eventos

class BloodRequester extends Actor {

implicit val executor = context.dispatcher

override def receive: Receive = { case BloodRequest(request) => DonorDAO.findNear(request).map { donors => donors.foreach { donor => facebookNotifier ! FacebookNotify(donor, request) } } }

}

Se reinician en caso de fallas

Supervisión

Page 20: Scala for rubyists

ScalaTest

Test Unit

trait NeoTest extends FunSpec with MustMatchers with BeforeAndAfterAll with BeforeAndAfterEach {override def beforeEach(): Unit = {

NeoDBCleaner.cleanDB()}describe("UserDAOs") {

it("creates an user an checks the default group") { withUser { (user, saved) => saved must be(true) val query = s"""match (a:user {id: "${user.id.getOrElse("")}"})-[c:has_group]->(b:group) return a, b, c""" val result = Await.result(NeoQuery.executeQuery[UserLogin, Group, HasGroupLogin](query), 2 seconds) result.length must be(1) } }}}

Multiples Pardigmas

TDD

BDD

Page 21: Scala for rubyists

Scala wants U ;)

https://www.coursera.org/course/progfun

http://scala-exercises.47deg.com/koans