SlideShare a Scribd company logo
Scala for Rubyists
Make your ideas come true
by Michel Perez
www.mrkaspa.com
Ruby :D
FELICIDAD TIPADO DINAMICO GEMS
NO IDE DOCUMENTACION FACIL DE APRENDER
Ruby :(
PERFORMANCE ESCALABILIDAD PROG FUNCIONAL
MANTENIBILIDAD CONCURRENCIA
Scala for rubyists
I <3 Java
- JVM
- Libraries
- Performance
- Escalabilidad
- Mantenibilidad
SCALA CLOJURE
JRUBYGROOVY
6
7
PROS CONS
Primitivas de concurrencia
Desarrollado por Google
Tiempo de compilación
Lenguaje compilado
Lenguaje tipado
Sintaxis old style
Demasiado imperativo
Poco funcional
Inmutabilidad
8
PROS CONS
Primitivas de concurrencia
Erlang
Lenguaje interpretado
Funcional
Muy nuevo
9
PROS CONS
Primitivas de concurrencia
Funcional
JVM
Lenguaje interpretado
Sistema de tipado opcional
LISP
10
PROS CONS
Akka
Funcional
JVM
Tipado
Compilado
Tiempo de compilación
Curva de aprendizaje
Gestión de dependencias
Programacion funcional
FUNCIONES Y MAS FUNCIONES INMUTABILIDAD
CURRYING CLOSURES
LAZY EVALUATION PATTERN MATCHING
CAMBIA LA MANERA EN COMO
PROGRAMAS
Scala Variables?
12
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
13
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
14
Case class -> get, set, constructor auto
Traits son similares a los modulos
en 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
15
Toda funciona debe tener un tipo de
retorno(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 Matching
16
Es 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
Implicits
17
Parametros inyectados en un metodo
o 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)
Monads
18
map, 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
Actors
19
Hilos 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
20
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 ;)
21
https://www.coursera.org/course/progfun
http://scala-exercises.47deg.com/koans

More Related Content

PPTX
Why TypeScript?
PDF
Elm kyivfprog 2015
PDF
Csp scala wixmeetup2016
PDF
Gatling - Paris Perf User Group
PPTX
Kotlin on android
PDF
Scala in Practice
PDF
scala-gopher: async implementation of CSP for scala
Why TypeScript?
Elm kyivfprog 2015
Csp scala wixmeetup2016
Gatling - Paris Perf User Group
Kotlin on android
Scala in Practice
scala-gopher: async implementation of CSP for scala

What's hot (20)

PDF
Building microservices with Kotlin
PDF
Introduction to Elm
PDF
Introduction to asynchronous DB access using Node.js and MongoDB
PDF
SE 20016 - programming languages landscape.
PPTX
Real cases of indispensability of Oracle SQL analytic functions
PDF
Swift and Kotlin Presentation
PDF
Introduction to Scala for Java Developers
PDF
Short intro to ECMAScript
PDF
Taking Kotlin to production, Seriously
ODP
A Tour Of Scala
PPTX
Kotlin For Android - Basics (part 1 of 7)
PPTX
Intro to Functional Programming in Scala
ZIP
Oral presentation v2
PPTX
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
PDF
LINQ Inside
KEY
Incremental Development with Lisp: Building a Game and a Website
KEY
Alfresco the clojure way
PPTX
.NET Foundation, Future of .NET and C#
PPTX
Elm: Make Yourself A Happy Front-end Web Developer
PPTX
C# Today and Tomorrow
Building microservices with Kotlin
Introduction to Elm
Introduction to asynchronous DB access using Node.js and MongoDB
SE 20016 - programming languages landscape.
Real cases of indispensability of Oracle SQL analytic functions
Swift and Kotlin Presentation
Introduction to Scala for Java Developers
Short intro to ECMAScript
Taking Kotlin to production, Seriously
A Tour Of Scala
Kotlin For Android - Basics (part 1 of 7)
Intro to Functional Programming in Scala
Oral presentation v2
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
LINQ Inside
Incremental Development with Lisp: Building a Game and a Website
Alfresco the clojure way
.NET Foundation, Future of .NET and C#
Elm: Make Yourself A Happy Front-end Web Developer
C# Today and Tomorrow
Ad

Viewers also liked (20)

PPTX
los bracekts
PDF
Adquirir una propiedad en españa en 7 pasos
PPT
Magonia getxo blog
PPTX
Pairform cci formpro
DOC
Copa menstrual y esponjas vaginales
PPT
Servidor web lamp
PDF
Dossier ii torneo once caballeros c.f.
PDF
2013 brand id&print
PPTX
Una modesta proposición
DOCX
Historia parte 2
PPSX
Av technika 4
PDF
Project Management Diploma with Instructors
PDF
9Guia1
PDF
C2B2 vFabric Hyperic Kickstart
PPTX
Tams 2012
PDF
Accesus - Catalogo andamio para vias ferroviarias
PPTX
Presentacion corporativa sevenminds agosto2012 (1)
PPTX
Principios de Diseño Sustentable (resumen)
PDF
Catalogo CTM 2015
los bracekts
Adquirir una propiedad en españa en 7 pasos
Magonia getxo blog
Pairform cci formpro
Copa menstrual y esponjas vaginales
Servidor web lamp
Dossier ii torneo once caballeros c.f.
2013 brand id&print
Una modesta proposición
Historia parte 2
Av technika 4
Project Management Diploma with Instructors
9Guia1
C2B2 vFabric Hyperic Kickstart
Tams 2012
Accesus - Catalogo andamio para vias ferroviarias
Presentacion corporativa sevenminds agosto2012 (1)
Principios de Diseño Sustentable (resumen)
Catalogo CTM 2015
Ad

Similar to Scala for rubyists (20)

PPT
Scala in a nutshell by venkat
PDF
Scala for Java Programmers
PPTX
Functional programming with Ruby - can make you look smart
PDF
Introduction to Functional Programming with Scala
PDF
Introduction to scala
PDF
The Evolution of Async-Programming (SD 2.0, JavaScript)
PDF
Intro to Functional Programming
PDF
Scala - just good for Java shops?
PDF
Scala is java8.next()
PDF
Kotlin boost yourproductivity
PDF
Coding in Style
PDF
Introduction to clojure
PDF
20160520 what youneedtoknowaboutlambdas
PDF
Introduction to Asynchronous scala
PDF
Scala in Places API
PDF
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
PDF
FP in Java - Project Lambda and beyond
PDF
The Kotlin Programming Language, Svetlana Isakova
PDF
Светлана Исакова «Язык Kotlin»
ODP
Scala in a nutshell by venkat
Scala for Java Programmers
Functional programming with Ruby - can make you look smart
Introduction to Functional Programming with Scala
Introduction to scala
The Evolution of Async-Programming (SD 2.0, JavaScript)
Intro to Functional Programming
Scala - just good for Java shops?
Scala is java8.next()
Kotlin boost yourproductivity
Coding in Style
Introduction to clojure
20160520 what youneedtoknowaboutlambdas
Introduction to Asynchronous scala
Scala in Places API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
FP in Java - Project Lambda and beyond
The Kotlin Programming Language, Svetlana Isakova
Светлана Исакова «Язык Kotlin»

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Empathic Computing: Creating Shared Understanding
PDF
Encapsulation theory and applications.pdf
PPTX
Cloud computing and distributed systems.
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
Teaching material agriculture food technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
sap open course for s4hana steps from ECC to s4
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Per capita expenditure prediction using model stacking based on satellite ima...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
“AI and Expert System Decision Support & Business Intelligence Systems”
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Programs and apps: productivity, graphics, security and other tools
Empathic Computing: Creating Shared Understanding
Encapsulation theory and applications.pdf
Cloud computing and distributed systems.
Agricultural_Statistics_at_a_Glance_2022_0.pdf
The AUB Centre for AI in Media Proposal.docx
20250228 LYD VKU AI Blended-Learning.pptx
Chapter 3 Spatial Domain Image Processing.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Teaching material agriculture food technology
Building Integrated photovoltaic BIPV_UPV.pdf
sap open course for s4hana steps from ECC to s4

Scala for rubyists

  • 1. Scala for Rubyists Make your ideas come true by Michel Perez www.mrkaspa.com
  • 2. Ruby :D FELICIDAD TIPADO DINAMICO GEMS NO IDE DOCUMENTACION FACIL DE APRENDER
  • 3. Ruby :( PERFORMANCE ESCALABILIDAD PROG FUNCIONAL MANTENIBILIDAD CONCURRENCIA
  • 5. I <3 Java - JVM - Libraries - Performance - Escalabilidad - Mantenibilidad SCALA CLOJURE JRUBYGROOVY
  • 6. 6
  • 7. 7 PROS CONS Primitivas de concurrencia Desarrollado por Google Tiempo de compilación Lenguaje compilado Lenguaje tipado Sintaxis old style Demasiado imperativo Poco funcional Inmutabilidad
  • 8. 8 PROS CONS Primitivas de concurrencia Erlang Lenguaje interpretado Funcional Muy nuevo
  • 9. 9 PROS CONS Primitivas de concurrencia Funcional JVM Lenguaje interpretado Sistema de tipado opcional LISP
  • 10. 10 PROS CONS Akka Funcional JVM Tipado Compilado Tiempo de compilación Curva de aprendizaje Gestión de dependencias
  • 11. Programacion funcional FUNCIONES Y MAS FUNCIONES INMUTABILIDAD CURRYING CLOSURES LAZY EVALUATION PATTERN MATCHING CAMBIA LA MANERA EN COMO PROGRAMAS
  • 12. Scala Variables? 12 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 ?
  • 13. Scala OOP + FP 13 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
  • 14. Scala OOP 14 Case class -> get, set, constructor auto Traits son similares a los modulos en 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] {
  • 15. Scala Functions 15 Toda funciona debe tener un tipo de retorno(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
  • 16. Pattern Matching 16 Es 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
  • 17. Implicits 17 Parametros inyectados en un metodo o 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)
  • 18. Monads 18 map, 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
  • 19. Actors 19 Hilos 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
  • 20. ScalaTest 20 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
  • 21. Scala wants U ;) 21 https://www.coursera.org/course/progfun http://scala-exercises.47deg.com/koans