SlideShare uma empresa Scribd logo
1 de 48
Baixar para ler offline
What Can Scala Puzzlers
Teach Us?
Daniel C. Sobral
Disclaimer #1: "Puzzlers"
● Java Puzzlers (the book/presentations):
○ Weird behavior in Java that is difficult to predict or
explain
● This presentation:
○ Weird behavior in Scala that confounds beginners
■ (and sometimes experienced programmers)
○ FAQs, not Fun
I can't speak for any of the people who
contributed to create and turn Scala into what it
is. Furthermore, if you learn anything from this
presentation, learn that a perfect understanding
of Scala is an unlikely achievement...
Disclaimer #2: don't trust me.
Symbols, operators and punctuation
● What does it mean?
● Where can I find information about it?
● WTF?
The symbol puzzler
Source: Stack Overflow
The Origin of the Symbols
● Punctuation elements of the language
○ @ # ( ) [ ] { } , . ; : ` ' "
● Keywords, reserved symbols and XML
○ <- => <: >: <% // /* */ _* <? <!
● Normal definitions from libraries
○ <:< =:= ☆ ★ η :/
● Underscore
○ All of the above!
Symbols may be part of the language or come
from external libraries; it can be difficult to tell
where they begin and end; they are difficult to
search for on the Internet, non-mnemonic and
unpronounceable.
Then why?
def f(xs: Array[Int], a: Int, b: Int) =
for (i <- xs.indices)
xs(i) = a * i + b
So that libraries can extend the
language seamlessly
def f(xs: M[T], a: T, b: T) =
for (i <- xs.indices)
xs(i) = a * i + b
For M and T library-types that support these
operations
Which still doesn't really justify unicode...
Advice regarding Symbols
● Learn the language:
○ What symbols are "built-in"
○ The syntax rules
● If exploring code using unknown libraries,
○ Use an IDE to explore it
harsh, indeed...
implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = {
new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] {
def id[A] = ☆(_ η)
def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g
}
}
Let's try to figure this one out
implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = {
new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] {
def id[A] = ☆(_ η)
def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g
}
}
Split Scala Syntax from Identifiers
implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = {
new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] {
def id[A] = ☆(_ η)
def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g
}
}
Identify what we are defining
implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = {
new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] {
def id[A] = ☆(_ η)
def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g
}
}
Where we are using our definitions
implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = {
new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] {
def id[A] = ☆(_ η)
def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g
}
}
What's left are outside identifiers
The Underscore
● What does it mean?
● Why does it work here but not here?
● WTF?
● It's everywhere! It's the borg operator!
One underscore puzzler
Source: Stack overflow
The meanings of underscore
Source: myself, by way of Stack Overflow
The underscore is Scala's wildcard; it means
"something" or "anything" and even "nothing".
However, it's semantics can be widely different,
even in similar contexts.
Why?
● ???
● Picking a different symbol for each case
would stretch ASCII
● Picking keywords is not in the spirit of Scala
● They are somewhat intuitive
○ except when they bite you
Advice regarding underscore
● Intuition does go a long way
● But, again, learn the language
● And, in particular, know the difference
between these:
○ f _
○ f(_, y)
○ f(x + _, y)
Eta, partial function application and
placeholders
● f _
○ an eta expansion: turn method f into an anonymous function.
● f(_, y)
○ a partial function application: creates an anonymous function from
method f, whose parameters are the ones wholly replaced by
underscores.
● f(x + _, y)
○ a placeholder: creates an anonymous function from the expression "x
+ _", whose parameters are the underscores (and that function gets
passed to f).
_ always picks the tightest non-degenerate
scope it can
Seth Tisue
Erasure
● Where are my types?
● How do I get them back?
● WTF?
Some things that don't work
trait X {
def overload(f: Int => Int)
def overload(f: String => String)
}
Some things that don't work
def f[T](list: List[T]) = list match {
case _: List[Int] => "Ints"
case _: List[String] => "Strings"
case _ => "???"
}
Some things that don't work
class C[T] {
def f(obj: Any) = obj match {
case _: T => "Ours"
case _ => "Not Ours"
}
}
Why?
● JVM does not support "type parameters"
● If Scala added metadata to "eliminate"
erasure, the interaction gap between it and
Java would be much greater
○ Though things like implicits and default parameters
already do it, to some extent
○ At least, implicits and defaults are easy to avoid
Some things that don't work
trait X {
def overload(f: Function1[Int, Int])
def overload(f: Function1[String,
String])
}
Erasure at work
trait X {
def overload(f: Function1)
def overload(f: Function1)
}
Erasure at work
def f(list: List) = list match {
case _: List => "Ints"
case _: List => "Strings"
case _ => "???"
}
Erasure at work
class C {
def f(obj: Any) = obj match {
case _: Any => "Ours"
case _ => "Not Ours"
}
}
A partial solution
class C[T : ClassTag] {
def f(obj: Any) = obj match {
case _: T => "Ours"
case _ => "Not Ours"
}
} though it will still ignore T's type parameters
Initialization Order
trait A {
val a: Int
val b = a * 2
}
class B extends A {
val a = 5
println(b)
}
new B
All val’s are initialized in the order they
are found.
Initialization Order
trait A {
val foo: Int
val bar = 10
println("In A: foo: " + foo + ", bar: " + bar)
}
class B extends A {
val foo: Int = 25
println("In B: foo: " + foo + ", bar: " + bar)
}
class C extends B {
override val bar = 99
println("In C: foo: " + foo + ", bar: " + bar)
}
new C
Source: Paul Phillips scala-faq by way of scala puzzlers
Initialization Order
In A: foo: 0, bar: 0
In B: foo: 25, bar: 0
In C: foo: 25, bar: 99
Initialization Order
trait A {
val foo: Int
val bar = 10
println("In A: foo: " + foo + ", bar: " + bar)
}
class B extends A {
val foo: Int = 25
println("In B: foo: " + foo + ", bar: " + bar)
}
class C extends B {
override val bar = 99
println("In C: foo: " + foo + ", bar: " + bar)
}
new C
A val is initialized only once.
Initialization Order
trait A { val x = 5 }
trait B {
val x: Int
println(x * 2)
}
trait C extends A with B
trait D extends B
class E extends D with C { println(x * 2) }
class F extends C with D { println(x * 2) }
new E
new F
Initialization Order
0
10
10
10
Initialization Order
trait A { val x = 5 }
trait B {
val x: Int
println(x * 2)
}
trait C extends A with B
trait D extends B
class E extends B with D with A with B with C { println(x * 2) }
class F extends A with B with C with B with D { println(x * 2) }
new E
new F
Trait linearization...
Advice regarding initialization order
● Learn the _________
Other things to look out for
● Pattern matching on val's and for's
● All sorts of things implicit
● Syntactic sugars, auto-tupling and the like
● The return keyword
So, what did I learn?
It seems to me that there's a wide range of
Scala features that depend on the user having
deep knowledge of the language when
something goes wrong. "What's going on?"
seems to be much more common than "How do
I do this?"
As for real Puzzlers...
● Site:
○ http://scalapuzzlers.com/
● Book:
○ http://www.artima.com/shop/scala_puzzlers

Mais conteúdo relacionado

Mais procurados

Crystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosCrystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosBrian Cardiff
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and conceptsNicola Bonelli
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaBrian Hsu
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginnerskenbot
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scalaPiotr Paradziński
 
Scala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysScala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysKonrad Malawski
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanJimin Hsieh
 
Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick referenceilesh raval
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Piotr Paradziński
 
Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersPiotr Paradziński
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Strong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisationStrong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisationDamien Seguy
 

Mais procurados (19)

Crystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosCrystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafios
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
Typeclasses
TypeclassesTypeclasses
Typeclasses
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
 
Scala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysScala Types of Types @ Lambda Days
Scala Types of Types @ Lambda Days
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Scala vs java 8
Scala vs java 8Scala vs java 8
Scala vs java 8
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick reference
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
Why functional programming and category theory strongly matters
Why functional programming and category theory strongly mattersWhy functional programming and category theory strongly matters
Why functional programming and category theory strongly matters
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Strong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisationStrong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisation
 

Semelhante a What can scala puzzlers teach us

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospectivechenge2k
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
IntroductiontoprogramminginscalaAmuhinda Hungai
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrongJulien Wetterwald
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into ScalaNehal Shah
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scalaakuklev
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersMiles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersChris
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)mircodotta
 
Elixir - GDG - Nantes
Elixir - GDG - NantesElixir - GDG - Nantes
Elixir - GDG - NantesAxel CATELAND
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Alexander Podkhalyuzin
 

Semelhante a What can scala puzzlers teach us (20)

Fancy talk
Fancy talkFancy talk
Fancy talk
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Elixir - GDG - Nantes
Elixir - GDG - NantesElixir - GDG - Nantes
Elixir - GDG - Nantes
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)
 

Mais de Daniel Sobral

Injecting Clock in Java
Injecting Clock in JavaInjecting Clock in Java
Injecting Clock in JavaDaniel Sobral
 
A JSR-310 Date: Beyond JODA Time
A JSR-310 Date: Beyond JODA TimeA JSR-310 Date: Beyond JODA Time
A JSR-310 Date: Beyond JODA TimeDaniel Sobral
 
Gestão automática de configuração usando puppet
Gestão automática de configuração usando puppetGestão automática de configuração usando puppet
Gestão automática de configuração usando puppetDaniel Sobral
 
Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Daniel Sobral
 
Palestra ganeti puppet
Palestra ganeti puppetPalestra ganeti puppet
Palestra ganeti puppetDaniel Sobral
 
Akka - Uma plataforma para o desenvolvimento de sistemas concorrentes e distr...
Akka - Uma plataforma para o desenvolvimento de sistemas concorrentes e distr...Akka - Uma plataforma para o desenvolvimento de sistemas concorrentes e distr...
Akka - Uma plataforma para o desenvolvimento de sistemas concorrentes e distr...Daniel Sobral
 

Mais de Daniel Sobral (10)

Injecting Clock in Java
Injecting Clock in JavaInjecting Clock in Java
Injecting Clock in Java
 
A JSR-310 Date: Beyond JODA Time
A JSR-310 Date: Beyond JODA TimeA JSR-310 Date: Beyond JODA Time
A JSR-310 Date: Beyond JODA Time
 
Gestão automática de configuração usando puppet
Gestão automática de configuração usando puppetGestão automática de configuração usando puppet
Gestão automática de configuração usando puppet
 
Scala 2.10.0 (english version)
Scala 2.10.0 (english version)Scala 2.10.0 (english version)
Scala 2.10.0 (english version)
 
Scala 2.10.0
Scala 2.10.0Scala 2.10.0
Scala 2.10.0
 
Palestra ganeti puppet
Palestra ganeti puppetPalestra ganeti puppet
Palestra ganeti puppet
 
Tutorial Puppet
Tutorial PuppetTutorial Puppet
Tutorial Puppet
 
Regex
RegexRegex
Regex
 
Introdução a TDD
Introdução a TDDIntrodução a TDD
Introdução a TDD
 
Akka - Uma plataforma para o desenvolvimento de sistemas concorrentes e distr...
Akka - Uma plataforma para o desenvolvimento de sistemas concorrentes e distr...Akka - Uma plataforma para o desenvolvimento de sistemas concorrentes e distr...
Akka - Uma plataforma para o desenvolvimento de sistemas concorrentes e distr...
 

Último

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Último (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

What can scala puzzlers teach us

  • 1. What Can Scala Puzzlers Teach Us? Daniel C. Sobral
  • 2. Disclaimer #1: "Puzzlers" ● Java Puzzlers (the book/presentations): ○ Weird behavior in Java that is difficult to predict or explain ● This presentation: ○ Weird behavior in Scala that confounds beginners ■ (and sometimes experienced programmers) ○ FAQs, not Fun
  • 3. I can't speak for any of the people who contributed to create and turn Scala into what it is. Furthermore, if you learn anything from this presentation, learn that a perfect understanding of Scala is an unlikely achievement... Disclaimer #2: don't trust me.
  • 4. Symbols, operators and punctuation ● What does it mean? ● Where can I find information about it? ● WTF?
  • 5. The symbol puzzler Source: Stack Overflow
  • 6. The Origin of the Symbols ● Punctuation elements of the language ○ @ # ( ) [ ] { } , . ; : ` ' " ● Keywords, reserved symbols and XML ○ <- => <: >: <% // /* */ _* <? <! ● Normal definitions from libraries ○ <:< =:= ☆ ★ η :/ ● Underscore ○ All of the above!
  • 7. Symbols may be part of the language or come from external libraries; it can be difficult to tell where they begin and end; they are difficult to search for on the Internet, non-mnemonic and unpronounceable.
  • 8. Then why? def f(xs: Array[Int], a: Int, b: Int) = for (i <- xs.indices) xs(i) = a * i + b
  • 9. So that libraries can extend the language seamlessly def f(xs: M[T], a: T, b: T) = for (i <- xs.indices) xs(i) = a * i + b For M and T library-types that support these operations
  • 10. Which still doesn't really justify unicode...
  • 11. Advice regarding Symbols ● Learn the language: ○ What symbols are "built-in" ○ The syntax rules ● If exploring code using unknown libraries, ○ Use an IDE to explore it harsh, indeed...
  • 12. implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = { new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] { def id[A] = ☆(_ η) def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g } } Let's try to figure this one out
  • 13. implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = { new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] { def id[A] = ☆(_ η) def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g } } Split Scala Syntax from Identifiers
  • 14. implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = { new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] { def id[A] = ☆(_ η) def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g } } Identify what we are defining
  • 15. implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = { new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] { def id[A] = ☆(_ η) def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g } } Where we are using our definitions
  • 16. implicit def KleisliCategory[M[_] : Monad]: Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] = { new Category[({type λ[α, β] = Kleisli[M, α, β]})#λ] { def id[A] = ☆(_ η) def compose[X, Y, Z](f: Kleisli[M, Y, Z], g: Kleisli[M, X, Y]) = f <=< g } } What's left are outside identifiers
  • 17. The Underscore ● What does it mean? ● Why does it work here but not here? ● WTF? ● It's everywhere! It's the borg operator!
  • 19. The meanings of underscore Source: myself, by way of Stack Overflow
  • 20. The underscore is Scala's wildcard; it means "something" or "anything" and even "nothing". However, it's semantics can be widely different, even in similar contexts.
  • 21. Why? ● ??? ● Picking a different symbol for each case would stretch ASCII ● Picking keywords is not in the spirit of Scala ● They are somewhat intuitive ○ except when they bite you
  • 22. Advice regarding underscore ● Intuition does go a long way ● But, again, learn the language ● And, in particular, know the difference between these: ○ f _ ○ f(_, y) ○ f(x + _, y)
  • 23. Eta, partial function application and placeholders ● f _ ○ an eta expansion: turn method f into an anonymous function. ● f(_, y) ○ a partial function application: creates an anonymous function from method f, whose parameters are the ones wholly replaced by underscores. ● f(x + _, y) ○ a placeholder: creates an anonymous function from the expression "x + _", whose parameters are the underscores (and that function gets passed to f).
  • 24. _ always picks the tightest non-degenerate scope it can Seth Tisue
  • 25. Erasure ● Where are my types? ● How do I get them back? ● WTF?
  • 26. Some things that don't work trait X { def overload(f: Int => Int) def overload(f: String => String) }
  • 27. Some things that don't work def f[T](list: List[T]) = list match { case _: List[Int] => "Ints" case _: List[String] => "Strings" case _ => "???" }
  • 28. Some things that don't work class C[T] { def f(obj: Any) = obj match { case _: T => "Ours" case _ => "Not Ours" } }
  • 29. Why? ● JVM does not support "type parameters" ● If Scala added metadata to "eliminate" erasure, the interaction gap between it and Java would be much greater ○ Though things like implicits and default parameters already do it, to some extent ○ At least, implicits and defaults are easy to avoid
  • 30. Some things that don't work trait X { def overload(f: Function1[Int, Int]) def overload(f: Function1[String, String]) }
  • 31. Erasure at work trait X { def overload(f: Function1) def overload(f: Function1) }
  • 32. Erasure at work def f(list: List) = list match { case _: List => "Ints" case _: List => "Strings" case _ => "???" }
  • 33. Erasure at work class C { def f(obj: Any) = obj match { case _: Any => "Ours" case _ => "Not Ours" } }
  • 34. A partial solution class C[T : ClassTag] { def f(obj: Any) = obj match { case _: T => "Ours" case _ => "Not Ours" } } though it will still ignore T's type parameters
  • 35. Initialization Order trait A { val a: Int val b = a * 2 } class B extends A { val a = 5 println(b) } new B
  • 36. All val’s are initialized in the order they are found.
  • 37. Initialization Order trait A { val foo: Int val bar = 10 println("In A: foo: " + foo + ", bar: " + bar) } class B extends A { val foo: Int = 25 println("In B: foo: " + foo + ", bar: " + bar) } class C extends B { override val bar = 99 println("In C: foo: " + foo + ", bar: " + bar) } new C Source: Paul Phillips scala-faq by way of scala puzzlers
  • 38. Initialization Order In A: foo: 0, bar: 0 In B: foo: 25, bar: 0 In C: foo: 25, bar: 99
  • 39. Initialization Order trait A { val foo: Int val bar = 10 println("In A: foo: " + foo + ", bar: " + bar) } class B extends A { val foo: Int = 25 println("In B: foo: " + foo + ", bar: " + bar) } class C extends B { override val bar = 99 println("In C: foo: " + foo + ", bar: " + bar) } new C
  • 40. A val is initialized only once.
  • 41. Initialization Order trait A { val x = 5 } trait B { val x: Int println(x * 2) } trait C extends A with B trait D extends B class E extends D with C { println(x * 2) } class F extends C with D { println(x * 2) } new E new F
  • 43. Initialization Order trait A { val x = 5 } trait B { val x: Int println(x * 2) } trait C extends A with B trait D extends B class E extends B with D with A with B with C { println(x * 2) } class F extends A with B with C with B with D { println(x * 2) } new E new F
  • 45. Advice regarding initialization order ● Learn the _________
  • 46. Other things to look out for ● Pattern matching on val's and for's ● All sorts of things implicit ● Syntactic sugars, auto-tupling and the like ● The return keyword
  • 47. So, what did I learn? It seems to me that there's a wide range of Scala features that depend on the user having deep knowledge of the language when something goes wrong. "What's going on?" seems to be much more common than "How do I do this?"
  • 48. As for real Puzzlers... ● Site: ○ http://scalapuzzlers.com/ ● Book: ○ http://www.artima.com/shop/scala_puzzlers