scala for rubyists

Post on 12-Apr-2017

194 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Scala for RubyistsMake your ideas come true

by Michel Perezwww.mrkaspa.com

Ruby :D

FELICIDAD TIPADO DINAMICO GEMS

NO IDE DOCUMENTACION FACIL DE APRENDER

Ruby :(

PERFORMANCE ESCALABILIDAD PROG FUNCIONAL

MANTENIBILIDAD CONCURRENCIA

I <3 Java

- JVM- Libraries- Performance- Escalabilidad- Mantenibilidad

SCALA CLOJURE

JRUBYGROOVY

PROS CONS

Primitivas de concurrencia

Desarrollado por Google

Tiempo de compilación

Lenguaje compilado

Lenguaje tipado

Sintaxis old style

Demasiado imperativo

Poco funcional

Inmutabilidad

PROS CONS

Primitivas de concurrencia

Erlang

Lenguaje interpretado

Funcional

Muy nuevo

PROS CONS

Primitivas de concurrencia

Funcional

JVM

Lenguaje interpretado

Sistema de tipado opcional

LISP

PROS CONS

Akka

Funcional

JVM

Tipado

Compilado

Tiempo de compilación

Curva de aprendizaje

Gestión de dependencias

Programacion funcionalFUNCIONES Y MAS FUNCIONES

INMUTABILIDAD

CURRYING CLOSURES

LAZY EVALUATION PATTERN MATCHING

CAMBIA LA MANERA EN COMO PROGRAMAS

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 ?

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

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] {

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

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

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)

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

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

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

Scala wants U ;)

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

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

top related