SlideShare a Scribd company logo
Scala
or: functional programming
from a python developer’s perspective
Gabriele Alese
http://gabale.se
Hello.
object HelloWorld extends App {
println("Hello World!")
}
apropos Scala
• «Scala is a pure-bred object-oriented language. Conceptually,
every value is an object and every operation is a method-call. The
language supports advanced component architectures through
classes and traits.»
• «Scala is also a full-blown functional language. It has everything
you would expect, including first-class functions, a library with
efficient immutable data structures, and a general preference of
immutability over mutation.»
• A sane approach to the JVM
• Flexibility
• Interoperability
• Excellent community
• Better documentation (mostly)
Why Scala?
• Static types
• Rich type system
• Functions are first-class citizens
• Stress on immutability
• Case classes (traits, objects, …)
• Pattern matching
• Rich collections (List, HashMap, Seq, Vector)
• Operator overloading
• Interoperability with Java libraries
• REPL and worksheets (Eclipse, IntelliJ)
Why I like Scala so much?
Static types
class Phrase(value: String) {
def wordCount: Map[String, Int] = {
val wordsMap = words map (_ -> 1)
wordsMap.foldLeft(Map.empty[String, Int]) {
case (acc, (key, _)) => acc + (key -> (acc.getOrElse(key, 0) + 1))
}
}
def words: Seq[String] = {
value.toLowerCase.split("[^a-zA-Z0-9']+")
}
}
Static types
• Compile time checking
• Your IDE will be much more helpful
• Encourages encapsulation
• Limits your ‘ability’ to write code before thinking
• Inferred types greatly reduce boilerplate
• … no more “‘NoneType’ object has no attribute…”

Rich type system
• Monads [Option, Try, Either, …]

«A monad is a container type together with map and flatMap methods defined on it.»
• Functions [Function1, Function2, …]
• Generic types [+T, -T]
• Higher kinded types

trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}
• Structural types

def setElementText(element : {def setText(text : String)}, text : String)
Functions as first-class citizens
sealed trait List[A] {
def map[A](f: A => A): List[A]
Functions as first-class citizens
• Higher-order functions (i.e. sum in terms of fold)
• Anonymous functions

(x: Int, y: Int) => x + y
• Easily transform collections with map
Stress on immutability
«[…] there can never be surprises in logic.»
– L. Wittgenstein
Hopefully, there should never be surprises in code.
Stress on immutability
object LongestIncreasingSubsequence {
def apply(sequence: Seq[Int]): Seq[Int] = {
val validSubsequences = iterateAndDropHead(Seq(sequence), sequence)
validSubsequences
.map(findIncreasingSubsequence)
.sortBy(_.length)(Ordering[Int].reverse)
.head
}
@tailrec
def iterateAndDropHead(folded: Seq[Seq[Int]], remaining: Seq[Int]): Seq[Seq[Int]] = {
remaining match {
case head :: Nil => folded
case head :: tail => iterateAndDropHead(folded :+ tail, tail)
}
}
def findIncreasingSubsequence(sequence: Seq[Int]): Seq[Int] = {
sequence.foldLeft(Seq(sequence.head)) {
(acc, el) => if(acc.last < el) acc :+ el else acc
}
}
}
Case classes
case class Person(firstName: String, lastName: String)
val randomGuy = Person("Gabriele", "Alese")
randomGuy match {
case Person("Gabriele", _) => println("Hello Gabriele!")
case Person("Vincent", _) => println("Hello, Vincent!")
case _ => println("I've never seen you before")
}
Case classes
• Free accessors (and mutators, if you must)
• Free equals() and hashCode()
• Free toString()
• Free copy()
• No need to use new
• Free apply and unapply methods 

on the companion object (see pattern matching)
Pattern matching
sealed abstract class Expression
case class X() extends Expression
case class Const(value : Int) extends Expression
case class Add(left : Expression, right : Expression) extends Expression
case class Mult(left : Expression, right : Expression) extends Expression
case class Neg(expr : Expression) extends Expression
def eval(expression : Expression, xValue : Int) : Int = expression match {
case X() => xValue
case Const(cst) => cst
case Add(left, right) => eval(left, xValue) + eval(right, xValue)
case Mult(left, right) => eval(left, xValue) * eval(right, xValue)
case Neg(expr) => - eval(expr, xValue)
}
Rich collections
def sort(xs: Array[Int]): Array[Int] = {
if (xs.length <= 1) xs
else {
val pivot = xs(xs.length / 2)
Array.concat(
sort(xs filter (pivot >)),
xs filter (pivot ==),
sort(xs filter (pivot <))
)
}
}
Rich collections
• map
• foreach
• filter (and filterNot)
• zip
• find
• drop (and dropWhile)
• foldLeft (and foldRight)
Rich collections
def dropWhile[A](l: List[A])(f: A => Boolean): List[A] =
l match {
case Cons(head, tail) if f(head) => dropWhile(tail)(f)
case _ => l
}
def foldRight[A, B](list: List[A], initial: B)(f: (A, B) => B): B = {
list match {
case Nil => initial
case Cons(head, tail) => f(head, foldRight(tail, initial)(f))
}
}
def foldLeft[A, B](as: List[A], initial: B)(f: (B, A) => B): B = {
as match {
case Nil => initial
case Cons(head, tail) => foldLeft(tail, f(initial, head))(f)
}
}
def map[A, B](list: List[A])(f: A => B): List[B] = {
foldRight(list, Nil: List[B])((a, b) => Cons(f(a), b))
}
def filter[A](list: List[A])(f: A => Boolean): List[A] = {
foldRight(list, Nil: List[A])((a, b) => if (f(a)) Cons(a, b) else b)
}
def flatMap[A, B](list: List[A])(f: A => List[B]): List[B] = {
concat(map(list)(f))
}
}
Operator overloading
package it.alese.scacchirossi.scacchirossi
import it.alese.scacchirossi.scacchirossi.board.{Column, Row}
case class Position(column: Column, row: Row) {
val x: Int = column.toInt
val y: Int = row.toInt
def to(toPosition: Position): List[Position] = {
Move(this, toPosition).intermediatePositions
}
def +(x: Int, y: Int) = {
val col = if (this.x + x != 0) Column(this.x + x) else this.column
val row = if (this.y + y != 0) Row(this.y + y) else this.row
new Position(col, row)
}
…
}
object Position {
def apply(position: String): Position = {
require(position.length == 2, "Illegal coordinate string")
new Position(Column(position(0)), Row(position(1).asDigit))
}
…
}
package it.alese.scacchirossi.scacchirossi
class PositionTest extends WordSpec with Matchers {
"A position" should {
…
"return a new position if summed to an offset" in {
Position("A1") + (1,1) shouldEqual Position("B2")
Position("A1") + (0,1) shouldEqual Position("A2")
}
"return a range of contiguous vertical positions" in {
Position("A1") to Position("A4")
shouldEqual
List(Position("A1"), Position("A2"), Position("A3"), Position("A4"))
}
}
Operator overloading
• Expressivity 

(especially combined with infix notation)
• Define intuitive operations between types
• Pretty powerful DSLs

(Like ScalaTest)
Interoperability with Java libraries
package it.alese.emailchecker
import java.io.{InputStreamReader, BufferedReader, PrintWriter}
import java.net.Socket
case class TelnetSession(socket: Socket, input: PrintWriter, output: BufferedReader) {
def allowsConnections: Boolean = {
Reply(output.readLine).code match {
case "220" => true
case _ => false
}
}
def send(command: String): String = {
input.println(command)
output.readLine
}
def close(): Unit = {
send("quit")
socket.close()
}
}
object TelnetSession {
def apply(host: String): TelnetSession = {
val socket = new Socket(host, 25)
new TelnetSession(
socket,
new PrintWriter(socket.getOutputStream, true),
new BufferedReader(
new InputStreamReader(socket.getInputStream)
)
)
}
}
Interoperability with Java libraries
• If you can’t find a Scala library for that, chances are
that you’ll find a Java equivalent

(Good luck with the documentation!)
• Appealing for Java programmers

(or young professionals fresh out of “university Java”)
• Stronger community

(IMHO: many Scala enthusiasts are Java seniors)
REPL
???
Thank you.
Gabriele Alese
http://gabale.se
Ad

More Related Content

What's hot (19)

Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
Knoldus Inc.
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Jorge Vásquez
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developers
ihji
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
Knoldus Inc.
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Scala Parallel Collections
Scala Parallel CollectionsScala Parallel Collections
Scala Parallel Collections
Aleksandar Prokopec
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
Raymond Tay
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
Knoldus Inc.
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
Jorge Vásquez
 
scala-101
scala-101scala-101
scala-101
Joe Conley
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
Jorge Vásquez
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
Nguyen Tuan
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
Knoldus Inc.
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Jorge Vásquez
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developers
ihji
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
Knoldus Inc.
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
Raymond Tay
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
Jorge Vásquez
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
Jorge Vásquez
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
Nguyen Tuan
 

Similar to Scala or functional programming from a python developer's perspective (20)

An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
Mohsen Zainalpour
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
Martin Ockajak
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
Constantine Nosovsky
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Yardena Meymann
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
Vasil Remeniuk
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
Kirill Kozlov
 
Scala
ScalaScala
Scala
suraj_atreya
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Short Reference Card for R users.
Short Reference Card for R users.Short Reference Card for R users.
Short Reference Card for R users.
Dr. Volkan OBAN
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
Martin Ockajak
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
Vasil Remeniuk
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Short Reference Card for R users.
Short Reference Card for R users.Short Reference Card for R users.
Short Reference Card for R users.
Dr. Volkan OBAN
 
Ad

Recently uploaded (20)

Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
MEMS IC Substrate Technologies Guide 2025.pptx
MEMS IC Substrate Technologies Guide 2025.pptxMEMS IC Substrate Technologies Guide 2025.pptx
MEMS IC Substrate Technologies Guide 2025.pptx
IC substrate Shawn Wang
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
How to Build an AI-Powered App: Tools, Techniques, and Trends
How to Build an AI-Powered App: Tools, Techniques, and TrendsHow to Build an AI-Powered App: Tools, Techniques, and Trends
How to Build an AI-Powered App: Tools, Techniques, and Trends
Nascenture
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
DNF 2.0 Implementations Challenges in Nepal
DNF 2.0 Implementations Challenges in NepalDNF 2.0 Implementations Challenges in Nepal
DNF 2.0 Implementations Challenges in Nepal
ICT Frame Magazine Pvt. Ltd.
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
MEMS IC Substrate Technologies Guide 2025.pptx
MEMS IC Substrate Technologies Guide 2025.pptxMEMS IC Substrate Technologies Guide 2025.pptx
MEMS IC Substrate Technologies Guide 2025.pptx
IC substrate Shawn Wang
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
How to Build an AI-Powered App: Tools, Techniques, and Trends
How to Build an AI-Powered App: Tools, Techniques, and TrendsHow to Build an AI-Powered App: Tools, Techniques, and Trends
How to Build an AI-Powered App: Tools, Techniques, and Trends
Nascenture
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Ad

Scala or functional programming from a python developer's perspective

  • 1. Scala or: functional programming from a python developer’s perspective Gabriele Alese http://gabale.se
  • 2. Hello. object HelloWorld extends App { println("Hello World!") }
  • 3. apropos Scala • «Scala is a pure-bred object-oriented language. Conceptually, every value is an object and every operation is a method-call. The language supports advanced component architectures through classes and traits.» • «Scala is also a full-blown functional language. It has everything you would expect, including first-class functions, a library with efficient immutable data structures, and a general preference of immutability over mutation.»
  • 4. • A sane approach to the JVM • Flexibility • Interoperability • Excellent community • Better documentation (mostly) Why Scala?
  • 5. • Static types • Rich type system • Functions are first-class citizens • Stress on immutability • Case classes (traits, objects, …) • Pattern matching • Rich collections (List, HashMap, Seq, Vector) • Operator overloading • Interoperability with Java libraries • REPL and worksheets (Eclipse, IntelliJ) Why I like Scala so much?
  • 6. Static types class Phrase(value: String) { def wordCount: Map[String, Int] = { val wordsMap = words map (_ -> 1) wordsMap.foldLeft(Map.empty[String, Int]) { case (acc, (key, _)) => acc + (key -> (acc.getOrElse(key, 0) + 1)) } } def words: Seq[String] = { value.toLowerCase.split("[^a-zA-Z0-9']+") } }
  • 7. Static types • Compile time checking • Your IDE will be much more helpful • Encourages encapsulation • Limits your ‘ability’ to write code before thinking • Inferred types greatly reduce boilerplate • … no more “‘NoneType’ object has no attribute…”

  • 8. Rich type system • Monads [Option, Try, Either, …]
 «A monad is a container type together with map and flatMap methods defined on it.» • Functions [Function1, Function2, …] • Generic types [+T, -T] • Higher kinded types
 trait Functor[F[_]] { def map[A, B](fa: F[A])(f: A => B): F[B] } • Structural types
 def setElementText(element : {def setText(text : String)}, text : String)
  • 9. Functions as first-class citizens sealed trait List[A] { def map[A](f: A => A): List[A]
  • 10. Functions as first-class citizens • Higher-order functions (i.e. sum in terms of fold) • Anonymous functions
 (x: Int, y: Int) => x + y • Easily transform collections with map
  • 11. Stress on immutability «[…] there can never be surprises in logic.» – L. Wittgenstein Hopefully, there should never be surprises in code.
  • 12. Stress on immutability object LongestIncreasingSubsequence { def apply(sequence: Seq[Int]): Seq[Int] = { val validSubsequences = iterateAndDropHead(Seq(sequence), sequence) validSubsequences .map(findIncreasingSubsequence) .sortBy(_.length)(Ordering[Int].reverse) .head } @tailrec def iterateAndDropHead(folded: Seq[Seq[Int]], remaining: Seq[Int]): Seq[Seq[Int]] = { remaining match { case head :: Nil => folded case head :: tail => iterateAndDropHead(folded :+ tail, tail) } } def findIncreasingSubsequence(sequence: Seq[Int]): Seq[Int] = { sequence.foldLeft(Seq(sequence.head)) { (acc, el) => if(acc.last < el) acc :+ el else acc } } }
  • 13. Case classes case class Person(firstName: String, lastName: String) val randomGuy = Person("Gabriele", "Alese") randomGuy match { case Person("Gabriele", _) => println("Hello Gabriele!") case Person("Vincent", _) => println("Hello, Vincent!") case _ => println("I've never seen you before") }
  • 14. Case classes • Free accessors (and mutators, if you must) • Free equals() and hashCode() • Free toString() • Free copy() • No need to use new • Free apply and unapply methods 
 on the companion object (see pattern matching)
  • 15. Pattern matching sealed abstract class Expression case class X() extends Expression case class Const(value : Int) extends Expression case class Add(left : Expression, right : Expression) extends Expression case class Mult(left : Expression, right : Expression) extends Expression case class Neg(expr : Expression) extends Expression def eval(expression : Expression, xValue : Int) : Int = expression match { case X() => xValue case Const(cst) => cst case Add(left, right) => eval(left, xValue) + eval(right, xValue) case Mult(left, right) => eval(left, xValue) * eval(right, xValue) case Neg(expr) => - eval(expr, xValue) }
  • 16. Rich collections def sort(xs: Array[Int]): Array[Int] = { if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <)) ) } }
  • 17. Rich collections • map • foreach • filter (and filterNot) • zip • find • drop (and dropWhile) • foldLeft (and foldRight)
  • 18. Rich collections def dropWhile[A](l: List[A])(f: A => Boolean): List[A] = l match { case Cons(head, tail) if f(head) => dropWhile(tail)(f) case _ => l } def foldRight[A, B](list: List[A], initial: B)(f: (A, B) => B): B = { list match { case Nil => initial case Cons(head, tail) => f(head, foldRight(tail, initial)(f)) } } def foldLeft[A, B](as: List[A], initial: B)(f: (B, A) => B): B = { as match { case Nil => initial case Cons(head, tail) => foldLeft(tail, f(initial, head))(f) } } def map[A, B](list: List[A])(f: A => B): List[B] = { foldRight(list, Nil: List[B])((a, b) => Cons(f(a), b)) } def filter[A](list: List[A])(f: A => Boolean): List[A] = { foldRight(list, Nil: List[A])((a, b) => if (f(a)) Cons(a, b) else b) } def flatMap[A, B](list: List[A])(f: A => List[B]): List[B] = { concat(map(list)(f)) } }
  • 19. Operator overloading package it.alese.scacchirossi.scacchirossi import it.alese.scacchirossi.scacchirossi.board.{Column, Row} case class Position(column: Column, row: Row) { val x: Int = column.toInt val y: Int = row.toInt def to(toPosition: Position): List[Position] = { Move(this, toPosition).intermediatePositions } def +(x: Int, y: Int) = { val col = if (this.x + x != 0) Column(this.x + x) else this.column val row = if (this.y + y != 0) Row(this.y + y) else this.row new Position(col, row) } … } object Position { def apply(position: String): Position = { require(position.length == 2, "Illegal coordinate string") new Position(Column(position(0)), Row(position(1).asDigit)) } … } package it.alese.scacchirossi.scacchirossi class PositionTest extends WordSpec with Matchers { "A position" should { … "return a new position if summed to an offset" in { Position("A1") + (1,1) shouldEqual Position("B2") Position("A1") + (0,1) shouldEqual Position("A2") } "return a range of contiguous vertical positions" in { Position("A1") to Position("A4") shouldEqual List(Position("A1"), Position("A2"), Position("A3"), Position("A4")) } }
  • 20. Operator overloading • Expressivity 
 (especially combined with infix notation) • Define intuitive operations between types • Pretty powerful DSLs
 (Like ScalaTest)
  • 21. Interoperability with Java libraries package it.alese.emailchecker import java.io.{InputStreamReader, BufferedReader, PrintWriter} import java.net.Socket case class TelnetSession(socket: Socket, input: PrintWriter, output: BufferedReader) { def allowsConnections: Boolean = { Reply(output.readLine).code match { case "220" => true case _ => false } } def send(command: String): String = { input.println(command) output.readLine } def close(): Unit = { send("quit") socket.close() } } object TelnetSession { def apply(host: String): TelnetSession = { val socket = new Socket(host, 25) new TelnetSession( socket, new PrintWriter(socket.getOutputStream, true), new BufferedReader( new InputStreamReader(socket.getInputStream) ) ) } }
  • 22. Interoperability with Java libraries • If you can’t find a Scala library for that, chances are that you’ll find a Java equivalent
 (Good luck with the documentation!) • Appealing for Java programmers
 (or young professionals fresh out of “university Java”) • Stronger community
 (IMHO: many Scala enthusiasts are Java seniors)
  • 23. REPL
  • 24. ???
  翻译: