SlideShare una empresa de Scribd logo
1 de 29
Picking up from session 1
OOP/modular
• named BitSet
• compound Channel with Logged
• refined Channel {def close(): Unit }
Functional
• parametrized List[Int]
• existential List[T] forSome {type T}
• higher-kinded List
Picking up from session 1
• Self types
• Type members
• Implicits
• Type classes
• Logic programming with types
• Shapeless
Reminder
Self types
trait S3Connector { this: S3Processor =>
val accessKey = "fadsf76asf576dsa"
// ...
}
Limits where you can mix this trait in, i.e., it will only work like this:
class S3App extends S3Processor with S3Connector {
// ...
}
Type members
Alternative to type parameters, i.e.:
trait StringCollection extends Collection[String] {
// ...
}
vs
trait StringCollection extends Collection {
type T = String
// ...
}
Can also be
• abstract, so you could remove the String part as well
• type bounded, e.g., type T <: java.io.Closeable
Type members
Mostly useful for dealing with covariance and mixin problems:
class Animal {
def eat(f: Food)
}
class Cow extends Animal {
// cows only eat grass!
}
Type members
Mostly useful for dealing with covariance problems:
class Animal {
type SuitableFood
def eat(f: SuitableFood)
}
class Cow extends Animal {
type SuitableFood = Grass
}
Type members
Can be helpful in reducing redundancy for mixins:
trait IntTreeHelper { this: Tree[Int] =>
// ...
}
class TreeProcessor extends Tree[Int] with IntTreeHelper =>
// ...
}
vs
trait IntTreeHelper { this: Tree =>
type T = Int
// ...
}
class TreeProcessor extends Tree with IntTreeHelper =>
// ...
}
Implicits
Invisible entities within current scope:
• Parameters
• Methods
• Classes
Can be quite sneaky so don’t overdo it!
Implicit parameters
• Only one implicit keyword in signature
• Should come last
• Generally good for hiding configuration objects
implicit val arg1 = 1
implicit val arg2 = 2L
def ghostprint(a: Int)(implicit b: Int, c: Long) = println(a,b,c)
Implicit parameters
abstract class JobWithConf(args: Args) extends Job(args) {
implicit val configurationOfHadoop = …
}
class MyJob(args: Args) extends JobWithConf(args) {
…
val folderContents = getHDFSContents(folder)
}
object HDFSUtil{
def getHDFSContents(in: String)(implicit configuration: Configuration): List[String] =
Option(FileSystem.get(configuration).globStatus(new Path(in))) match {
case Some(a) => a.toList
case None => Nil
}.map(_.getPath.getName)
}
Implicit parameters
Helpful predefined function is implicitly[T], which ”catches” an implicit:
def implicitly[T](implicit e: T): T = e
Actually, configurationOfHadoop from the previous slide is defined as
@transient implicit val configurationOfHadoop = implicitly[Mode] match {
case Hdfs(_, configuration) => configuration
case _ => sys.error("Not running on Hadoop!")
}
Implicit methods
Usually used to silently convert between types
class MyInt(val i: Int) {
def inc = new MyInt(i+1)
}
implicit def int2MyInt(i: Int) = new MyInt(i)
5.inc
Implicit classes
Same idea, used to “pimp your classes”:
implicit class MyInt(val i: Int) {
def inc = new MyInt(i+1)
}
5.inc
Implicit classes
You can also pimp companion objects:
implicit class SuperList(companion: List.type) {
def fillInterspersed[A](n: Int)(a: A, b: A) = …
}
View and context bounds
These are shortcuts for providing implicit conversions and wrappers:
// view bound
def f[A <% B](a: A) = a.bMethod
is equal to
def f[A](a: A)(implicit ev: A => B) = a.bMethod
// context bound
def g[A : B](a: A) = h(a)
is equal to
def g[A](a: A)(implicit ev: B[A]) = h(a)
Type classes
• come from Haskell
• no relation to OOP classes
• a facility for ad-hoc polymorphism (compile-time variant of subtype
p-m)
• in Scala they are basically traits + implicits (context bounds)
Type classes
trait Monoid[T] {
def zero: T
def append(a: T, b: T): T
}
implicit object IntIsMonoid extends Monoid[Int] {
def zero = 0
def append(a: Int, b: Int) = a + b
}
implicit object StringIsMonoid extends Monoid[String] {
def zero = ""
def append(a: String, b: String) = a concat b // try to avoid + for Strings
}
Type classes
def sum[T](xs: List[T])(implicit monoid: Monoid[T]) =
xs.foldLeft(monoid.zero)(monoid.append)
//context bounds
def sum[T : Monoid](xs: List[T]) = {
val monoid = implicitly[Monoid[T]]
xs.foldLeft(monoid.zero)(monoid.append)
}
Logic programming
• imperative - state = functional
• functional - DFS = logic
• Predicates/constraints instead of functions:
pow(2,3) = 8 ~ pow(2,3,8)
• Essentially an interface to a theorem prover
Prolog
• created in early 70s
• archetypical LP language
• Towers of Hanoi:
move(1, L, R, C) :-
write(['Move top disk from ', L , ' to ', R]),
nl.
move(N, L, R, C) :-
N > 1,
M is N - 1,
move(M, L, C, R),
move(1, L, R, C),
move(M, C, R, L).
move(3, L, R, C).
Logic programming
Scala implicit search engine is sort of a prover:
• facts = implicit vals
• rules = implicit defs
Towers of Hanoi
sealed trait Name
case object Left extends Name
case object Right extends Name
case object Center extends Name
trait Move[N <: Nat, L <: Name, R <: Name, C <: Name]
Towers of Hanoi
implicit def move0[L <: Name,
R <: Name,
C <: Name]: Move[_1, L, R, C] =
new Move[_1, L, R, C] {}
Towers of Hanoi
implicit def move1[N <: Nat,
M <: Nat,
L <: Name,
R <: Name,
C <: Name]
(implicit ev0 : LT[_1, N],
ev1 : Diff.Aux[N, _1, M],
ev2 : Move[M, L, C, R],
ev3 : Move[_1, L, R, C],
ev4 : Move[M, C, R, L]): Move[N, L, R, C] =
new Move[N, L, R, C] {}
Towers of Hanoi
implicitly[Move[_3, Left.type, Right.type, Center.type]]
Shapeless
• So what are these Nat, LT, Diff.Aux things?
• These are type-level numbers and arithmetical operations defined in a library called
Shapeless:
sealed trait Nat
sealed trait _0 extends Nat
sealed trait Succ[N <: Nat] extends Nat
type _1 = Succ[_0]
type _2 = Succ[_1]
...
trait LT[A <: Nat, B <: Nat]
object LT {
def apply[A <: Nat, B <: Nat](implicit lt: A < B): LT[A, B] = lt
type <[A <: Nat, B <: Nat] = LT[A, B]
implicit def lt1[B <: Nat] = new <[_0, Succ[B]] {}
implicit def lt2[A <: Nat, B <: Nat](implicit lt : A < B) = new <[Succ[A], Succ[B]] {}
}
Shapeless
• HLists: like tuples, but with variable arity and collection functionality
• (also can be created from case classes)
• HMap: bidirectional map, e.g. HMap[BiMapIS](23 -> "foo", "bar" -> 13)
• Coproducts: Like Either, but with arbitrary number of choices
• Lens: compositional getters and setters for nested case classes
• collections with statically known sizes
• typesafe casting (wrapping in an Option)
References
• http://debasishg.blogspot.com/2010/02/scala-self-type-annotations-for.html
• http://stackoverflow.com/questions/1154571/scala-abstract-types-vs-generics
• http://like-a-boss.net/2013/03/29/polymorphism-and-typeclasses-in-scala.html
• http://lanyrd.com/2014/scalaio-fr/sdgcwm
• https://apocalisp.wordpress.com/2010/06/08/type-level-programming-in-scala
• https://github.com/milessabin/shapeless/wiki/Feature-overview%3a-shapeless-
2.0.0

Más contenido relacionado

La actualidad más candente

La actualidad más candente (19)

09. haskell Context
09. haskell Context09. haskell Context
09. haskell Context
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick reference
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Templates
TemplatesTemplates
Templates
 
Array ppt
Array pptArray ppt
Array ppt
 
Text and Numbers (Data Types)in PHP
Text and Numbers (Data Types)in PHPText and Numbers (Data Types)in PHP
Text and Numbers (Data Types)in PHP
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
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
 
Python data handling
Python data handlingPython data handling
Python data handling
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Strings
StringsStrings
Strings
 

Destacado

Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform ResearchVasil Remeniuk
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin Vasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovVasil Remeniuk
 
Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Vasil Remeniuk
 
"Error Recovery" by @alaz at scalaby#8
"Error Recovery" by @alaz at scalaby#8"Error Recovery" by @alaz at scalaby#8
"Error Recovery" by @alaz at scalaby#8Vasil Remeniuk
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaVasil Remeniuk
 
Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Vasil Remeniuk
 
Spark by Adform Research, Paulius
Spark by Adform Research, PauliusSpark by Adform Research, Paulius
Spark by Adform Research, PauliusVasil Remeniuk
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Vasil Remeniuk
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaVasil Remeniuk
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin Vasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovVasil Remeniuk
 
Scala Magic, Alexander Podhaliusin
Scala Magic, Alexander PodhaliusinScala Magic, Alexander Podhaliusin
Scala Magic, Alexander PodhaliusinVasil Remeniuk
 
First glance at Akka 2.0
First glance at Akka 2.0First glance at Akka 2.0
First glance at Akka 2.0Vasil Remeniuk
 
Spark Intro by Adform Research
Spark Intro by Adform ResearchSpark Intro by Adform Research
Spark Intro by Adform ResearchVasil Remeniuk
 
Spark intro by Adform Research
Spark intro by Adform ResearchSpark intro by Adform Research
Spark intro by Adform ResearchVasil Remeniuk
 
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovParsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovVasil Remeniuk
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaVasil Remeniuk
 

Destacado (20)

Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
 
Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)
 
"Error Recovery" by @alaz at scalaby#8
"Error Recovery" by @alaz at scalaby#8"Error Recovery" by @alaz at scalaby#8
"Error Recovery" by @alaz at scalaby#8
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius Valatka
 
Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1
 
Spark by Adform Research, Paulius
Spark by Adform Research, PauliusSpark by Adform Research, Paulius
Spark by Adform Research, Paulius
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2
 
Vaadin+Scala
Vaadin+ScalaVaadin+Scala
Vaadin+Scala
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
 
Scala Magic, Alexander Podhaliusin
Scala Magic, Alexander PodhaliusinScala Magic, Alexander Podhaliusin
Scala Magic, Alexander Podhaliusin
 
First glance at Akka 2.0
First glance at Akka 2.0First glance at Akka 2.0
First glance at Akka 2.0
 
Spark Intro by Adform Research
Spark Intro by Adform ResearchSpark Intro by Adform Research
Spark Intro by Adform Research
 
Spark intro by Adform Research
Spark intro by Adform ResearchSpark intro by Adform Research
Spark intro by Adform Research
 
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix KliuchnikovParsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 

Similar a Types by Adform Research

Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectivegabalese
 
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 worldDebasish Ghosh
 
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 Scaladjspiewak
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1Hang Zhao
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 

Similar a Types by Adform Research (20)

Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
 
C# programming
C# programming C# programming
C# programming
 
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
 
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
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Thesis
ThesisThesis
Thesis
 
Thesis PPT
Thesis PPTThesis PPT
Thesis PPT
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 

Más de Vasil Remeniuk

Product Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикProduct Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикVasil Remeniuk
 
Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Vasil Remeniuk
 
Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Vasil Remeniuk
 
Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Vasil Remeniuk
 
Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by Adform researchVasil Remeniuk
 
Cassandra + Spark + Elk
Cassandra + Spark + ElkCassandra + Spark + Elk
Cassandra + Spark + ElkVasil Remeniuk
 
Опыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхОпыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхVasil Remeniuk
 
Funtional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTFuntional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTVasil Remeniuk
 
[Не]практичные типы
[Не]практичные типы[Не]практичные типы
[Не]практичные типыVasil Remeniuk
 
Зачем нужна Scala?
Зачем нужна Scala?Зачем нужна Scala?
Зачем нужна Scala?Vasil Remeniuk
 
a million bots can't be wrong
a million bots can't be wronga million bots can't be wrong
a million bots can't be wrongVasil Remeniuk
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako, Vasil Remeniuk
 

Más de Vasil Remeniuk (13)

Product Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикProduct Minsk - РТБ и Программатик
Product Minsk - РТБ и Программатик
 
Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14
 
Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14
 
Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3
 
Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by Adform research
 
Cassandra + Spark + Elk
Cassandra + Spark + ElkCassandra + Spark + Elk
Cassandra + Spark + Elk
 
Опыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхОпыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событиях
 
ETL со Spark
ETL со SparkETL со Spark
ETL со Spark
 
Funtional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTFuntional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWT
 
[Не]практичные типы
[Не]практичные типы[Не]практичные типы
[Не]практичные типы
 
Зачем нужна Scala?
Зачем нужна Scala?Зачем нужна Scala?
Зачем нужна Scala?
 
a million bots can't be wrong
a million bots can't be wronga million bots can't be wrong
a million bots can't be wrong
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 

Último

Asli Kala jadu, Black magic specialist in Pakistan Or Kala jadu expert in Egy...
Asli Kala jadu, Black magic specialist in Pakistan Or Kala jadu expert in Egy...Asli Kala jadu, Black magic specialist in Pakistan Or Kala jadu expert in Egy...
Asli Kala jadu, Black magic specialist in Pakistan Or Kala jadu expert in Egy...baharayali
 
WhatsApp Chat: 📞 8617697112 Birbhum Call Girl available for hotel room package
WhatsApp Chat: 📞 8617697112 Birbhum  Call Girl available for hotel room packageWhatsApp Chat: 📞 8617697112 Birbhum  Call Girl available for hotel room package
WhatsApp Chat: 📞 8617697112 Birbhum Call Girl available for hotel room packageNitya salvi
 
Sports Writing (Rules,Tips, Examples, etc)
Sports Writing (Rules,Tips, Examples, etc)Sports Writing (Rules,Tips, Examples, etc)
Sports Writing (Rules,Tips, Examples, etc)CMBustamante
 
Technical Data | Sig Sauer Easy6 BDX 1-6x24 | Optics Trade
Technical Data | Sig Sauer Easy6 BDX 1-6x24 | Optics TradeTechnical Data | Sig Sauer Easy6 BDX 1-6x24 | Optics Trade
Technical Data | Sig Sauer Easy6 BDX 1-6x24 | Optics TradeOptics-Trade
 
European Football Icons that Missed Opportunities at UEFA Euro 2024.docx
European Football Icons that Missed Opportunities at UEFA Euro 2024.docxEuropean Football Icons that Missed Opportunities at UEFA Euro 2024.docx
European Football Icons that Missed Opportunities at UEFA Euro 2024.docxEuro Cup 2024 Tickets
 
2k Shots ≽ 9205541914 ≼ Call Girls In Sheikh Sarai (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Sheikh Sarai (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Sheikh Sarai (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Sheikh Sarai (Delhi)Delhi Call girls
 
Who Is Emmanuel Katto Uganda? His Career, personal life etc.
Who Is Emmanuel Katto Uganda? His Career, personal life etc.Who Is Emmanuel Katto Uganda? His Career, personal life etc.
Who Is Emmanuel Katto Uganda? His Career, personal life etc.Marina Costa
 
Spain Vs Italy Spain to be banned from participating in Euro 2024.docx
Spain Vs Italy Spain to be banned from participating in Euro 2024.docxSpain Vs Italy Spain to be banned from participating in Euro 2024.docx
Spain Vs Italy Spain to be banned from participating in Euro 2024.docxWorld Wide Tickets And Hospitality
 
Cricket Api Solution.pdfCricket Api Solution.pdf
Cricket Api Solution.pdfCricket Api Solution.pdfCricket Api Solution.pdfCricket Api Solution.pdf
Cricket Api Solution.pdfCricket Api Solution.pdfLatiyalinfotech
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
JORNADA 6 LIGA MURO 2024TUXTEPECOAXACA.pdf
JORNADA 6 LIGA MURO 2024TUXTEPECOAXACA.pdfJORNADA 6 LIGA MURO 2024TUXTEPECOAXACA.pdf
JORNADA 6 LIGA MURO 2024TUXTEPECOAXACA.pdfArturo Pacheco Alvarez
 
Muzaffarpur Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Muzaffarpur Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMuzaffarpur Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Muzaffarpur Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Netherlands Players expected to miss UEFA Euro 2024 due to injury.docx
Netherlands Players expected to miss UEFA Euro 2024 due to injury.docxNetherlands Players expected to miss UEFA Euro 2024 due to injury.docx
Netherlands Players expected to miss UEFA Euro 2024 due to injury.docxEuro Cup 2024 Tickets
 
Hire 💕 8617697112 Kasauli Call Girls Service Call Girls Agency
Hire 💕 8617697112 Kasauli Call Girls Service Call Girls AgencyHire 💕 8617697112 Kasauli Call Girls Service Call Girls Agency
Hire 💕 8617697112 Kasauli Call Girls Service Call Girls AgencyNitya salvi
 
Personal Brand Exploration - By Bradley Dennis
Personal Brand Exploration - By Bradley DennisPersonal Brand Exploration - By Bradley Dennis
Personal Brand Exploration - By Bradley Dennisjocksofalltradespodc
 
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
JORNADA 5 LIGA MURO 2024INSUGURACION.pdf
JORNADA 5 LIGA MURO 2024INSUGURACION.pdfJORNADA 5 LIGA MURO 2024INSUGURACION.pdf
JORNADA 5 LIGA MURO 2024INSUGURACION.pdfArturo Pacheco Alvarez
 
Slovenia Vs Serbia UEFA Euro 2024 Fixture Guide Every Fixture Detailed.docx
Slovenia Vs Serbia UEFA Euro 2024 Fixture Guide Every Fixture Detailed.docxSlovenia Vs Serbia UEFA Euro 2024 Fixture Guide Every Fixture Detailed.docx
Slovenia Vs Serbia UEFA Euro 2024 Fixture Guide Every Fixture Detailed.docxWorld Wide Tickets And Hospitality
 
Albania Vs Spain South American coaches lead Albania to Euro 2024 spot.docx
Albania Vs Spain South American coaches lead Albania to Euro 2024 spot.docxAlbania Vs Spain South American coaches lead Albania to Euro 2024 spot.docx
Albania Vs Spain South American coaches lead Albania to Euro 2024 spot.docxWorld Wide Tickets And Hospitality
 
UEFA Euro 2024 Squad Check-in Which team is Top favorite.docx
UEFA Euro 2024 Squad Check-in Which team is Top favorite.docxUEFA Euro 2024 Squad Check-in Which team is Top favorite.docx
UEFA Euro 2024 Squad Check-in Which team is Top favorite.docxEuro Cup 2024 Tickets
 

Último (20)

Asli Kala jadu, Black magic specialist in Pakistan Or Kala jadu expert in Egy...
Asli Kala jadu, Black magic specialist in Pakistan Or Kala jadu expert in Egy...Asli Kala jadu, Black magic specialist in Pakistan Or Kala jadu expert in Egy...
Asli Kala jadu, Black magic specialist in Pakistan Or Kala jadu expert in Egy...
 
WhatsApp Chat: 📞 8617697112 Birbhum Call Girl available for hotel room package
WhatsApp Chat: 📞 8617697112 Birbhum  Call Girl available for hotel room packageWhatsApp Chat: 📞 8617697112 Birbhum  Call Girl available for hotel room package
WhatsApp Chat: 📞 8617697112 Birbhum Call Girl available for hotel room package
 
Sports Writing (Rules,Tips, Examples, etc)
Sports Writing (Rules,Tips, Examples, etc)Sports Writing (Rules,Tips, Examples, etc)
Sports Writing (Rules,Tips, Examples, etc)
 
Technical Data | Sig Sauer Easy6 BDX 1-6x24 | Optics Trade
Technical Data | Sig Sauer Easy6 BDX 1-6x24 | Optics TradeTechnical Data | Sig Sauer Easy6 BDX 1-6x24 | Optics Trade
Technical Data | Sig Sauer Easy6 BDX 1-6x24 | Optics Trade
 
European Football Icons that Missed Opportunities at UEFA Euro 2024.docx
European Football Icons that Missed Opportunities at UEFA Euro 2024.docxEuropean Football Icons that Missed Opportunities at UEFA Euro 2024.docx
European Football Icons that Missed Opportunities at UEFA Euro 2024.docx
 
2k Shots ≽ 9205541914 ≼ Call Girls In Sheikh Sarai (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Sheikh Sarai (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Sheikh Sarai (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Sheikh Sarai (Delhi)
 
Who Is Emmanuel Katto Uganda? His Career, personal life etc.
Who Is Emmanuel Katto Uganda? His Career, personal life etc.Who Is Emmanuel Katto Uganda? His Career, personal life etc.
Who Is Emmanuel Katto Uganda? His Career, personal life etc.
 
Spain Vs Italy Spain to be banned from participating in Euro 2024.docx
Spain Vs Italy Spain to be banned from participating in Euro 2024.docxSpain Vs Italy Spain to be banned from participating in Euro 2024.docx
Spain Vs Italy Spain to be banned from participating in Euro 2024.docx
 
Cricket Api Solution.pdfCricket Api Solution.pdf
Cricket Api Solution.pdfCricket Api Solution.pdfCricket Api Solution.pdfCricket Api Solution.pdf
Cricket Api Solution.pdfCricket Api Solution.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
JORNADA 6 LIGA MURO 2024TUXTEPECOAXACA.pdf
JORNADA 6 LIGA MURO 2024TUXTEPECOAXACA.pdfJORNADA 6 LIGA MURO 2024TUXTEPECOAXACA.pdf
JORNADA 6 LIGA MURO 2024TUXTEPECOAXACA.pdf
 
Muzaffarpur Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Muzaffarpur Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMuzaffarpur Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Muzaffarpur Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Netherlands Players expected to miss UEFA Euro 2024 due to injury.docx
Netherlands Players expected to miss UEFA Euro 2024 due to injury.docxNetherlands Players expected to miss UEFA Euro 2024 due to injury.docx
Netherlands Players expected to miss UEFA Euro 2024 due to injury.docx
 
Hire 💕 8617697112 Kasauli Call Girls Service Call Girls Agency
Hire 💕 8617697112 Kasauli Call Girls Service Call Girls AgencyHire 💕 8617697112 Kasauli Call Girls Service Call Girls Agency
Hire 💕 8617697112 Kasauli Call Girls Service Call Girls Agency
 
Personal Brand Exploration - By Bradley Dennis
Personal Brand Exploration - By Bradley DennisPersonal Brand Exploration - By Bradley Dennis
Personal Brand Exploration - By Bradley Dennis
 
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 62, Noida Call girls :8448380779 Model Escorts | 100% verified
 
JORNADA 5 LIGA MURO 2024INSUGURACION.pdf
JORNADA 5 LIGA MURO 2024INSUGURACION.pdfJORNADA 5 LIGA MURO 2024INSUGURACION.pdf
JORNADA 5 LIGA MURO 2024INSUGURACION.pdf
 
Slovenia Vs Serbia UEFA Euro 2024 Fixture Guide Every Fixture Detailed.docx
Slovenia Vs Serbia UEFA Euro 2024 Fixture Guide Every Fixture Detailed.docxSlovenia Vs Serbia UEFA Euro 2024 Fixture Guide Every Fixture Detailed.docx
Slovenia Vs Serbia UEFA Euro 2024 Fixture Guide Every Fixture Detailed.docx
 
Albania Vs Spain South American coaches lead Albania to Euro 2024 spot.docx
Albania Vs Spain South American coaches lead Albania to Euro 2024 spot.docxAlbania Vs Spain South American coaches lead Albania to Euro 2024 spot.docx
Albania Vs Spain South American coaches lead Albania to Euro 2024 spot.docx
 
UEFA Euro 2024 Squad Check-in Which team is Top favorite.docx
UEFA Euro 2024 Squad Check-in Which team is Top favorite.docxUEFA Euro 2024 Squad Check-in Which team is Top favorite.docx
UEFA Euro 2024 Squad Check-in Which team is Top favorite.docx
 

Types by Adform Research

  • 1. Picking up from session 1 OOP/modular • named BitSet • compound Channel with Logged • refined Channel {def close(): Unit } Functional • parametrized List[Int] • existential List[T] forSome {type T} • higher-kinded List
  • 2. Picking up from session 1 • Self types • Type members • Implicits • Type classes • Logic programming with types • Shapeless
  • 4. Self types trait S3Connector { this: S3Processor => val accessKey = "fadsf76asf576dsa" // ... } Limits where you can mix this trait in, i.e., it will only work like this: class S3App extends S3Processor with S3Connector { // ... }
  • 5. Type members Alternative to type parameters, i.e.: trait StringCollection extends Collection[String] { // ... } vs trait StringCollection extends Collection { type T = String // ... } Can also be • abstract, so you could remove the String part as well • type bounded, e.g., type T <: java.io.Closeable
  • 6. Type members Mostly useful for dealing with covariance and mixin problems: class Animal { def eat(f: Food) } class Cow extends Animal { // cows only eat grass! }
  • 7. Type members Mostly useful for dealing with covariance problems: class Animal { type SuitableFood def eat(f: SuitableFood) } class Cow extends Animal { type SuitableFood = Grass }
  • 8. Type members Can be helpful in reducing redundancy for mixins: trait IntTreeHelper { this: Tree[Int] => // ... } class TreeProcessor extends Tree[Int] with IntTreeHelper => // ... } vs trait IntTreeHelper { this: Tree => type T = Int // ... } class TreeProcessor extends Tree with IntTreeHelper => // ... }
  • 9. Implicits Invisible entities within current scope: • Parameters • Methods • Classes Can be quite sneaky so don’t overdo it!
  • 10. Implicit parameters • Only one implicit keyword in signature • Should come last • Generally good for hiding configuration objects implicit val arg1 = 1 implicit val arg2 = 2L def ghostprint(a: Int)(implicit b: Int, c: Long) = println(a,b,c)
  • 11. Implicit parameters abstract class JobWithConf(args: Args) extends Job(args) { implicit val configurationOfHadoop = … } class MyJob(args: Args) extends JobWithConf(args) { … val folderContents = getHDFSContents(folder) } object HDFSUtil{ def getHDFSContents(in: String)(implicit configuration: Configuration): List[String] = Option(FileSystem.get(configuration).globStatus(new Path(in))) match { case Some(a) => a.toList case None => Nil }.map(_.getPath.getName) }
  • 12. Implicit parameters Helpful predefined function is implicitly[T], which ”catches” an implicit: def implicitly[T](implicit e: T): T = e Actually, configurationOfHadoop from the previous slide is defined as @transient implicit val configurationOfHadoop = implicitly[Mode] match { case Hdfs(_, configuration) => configuration case _ => sys.error("Not running on Hadoop!") }
  • 13. Implicit methods Usually used to silently convert between types class MyInt(val i: Int) { def inc = new MyInt(i+1) } implicit def int2MyInt(i: Int) = new MyInt(i) 5.inc
  • 14. Implicit classes Same idea, used to “pimp your classes”: implicit class MyInt(val i: Int) { def inc = new MyInt(i+1) } 5.inc
  • 15. Implicit classes You can also pimp companion objects: implicit class SuperList(companion: List.type) { def fillInterspersed[A](n: Int)(a: A, b: A) = … }
  • 16. View and context bounds These are shortcuts for providing implicit conversions and wrappers: // view bound def f[A <% B](a: A) = a.bMethod is equal to def f[A](a: A)(implicit ev: A => B) = a.bMethod // context bound def g[A : B](a: A) = h(a) is equal to def g[A](a: A)(implicit ev: B[A]) = h(a)
  • 17. Type classes • come from Haskell • no relation to OOP classes • a facility for ad-hoc polymorphism (compile-time variant of subtype p-m) • in Scala they are basically traits + implicits (context bounds)
  • 18. Type classes trait Monoid[T] { def zero: T def append(a: T, b: T): T } implicit object IntIsMonoid extends Monoid[Int] { def zero = 0 def append(a: Int, b: Int) = a + b } implicit object StringIsMonoid extends Monoid[String] { def zero = "" def append(a: String, b: String) = a concat b // try to avoid + for Strings }
  • 19. Type classes def sum[T](xs: List[T])(implicit monoid: Monoid[T]) = xs.foldLeft(monoid.zero)(monoid.append) //context bounds def sum[T : Monoid](xs: List[T]) = { val monoid = implicitly[Monoid[T]] xs.foldLeft(monoid.zero)(monoid.append) }
  • 20. Logic programming • imperative - state = functional • functional - DFS = logic • Predicates/constraints instead of functions: pow(2,3) = 8 ~ pow(2,3,8) • Essentially an interface to a theorem prover
  • 21. Prolog • created in early 70s • archetypical LP language • Towers of Hanoi: move(1, L, R, C) :- write(['Move top disk from ', L , ' to ', R]), nl. move(N, L, R, C) :- N > 1, M is N - 1, move(M, L, C, R), move(1, L, R, C), move(M, C, R, L). move(3, L, R, C).
  • 22. Logic programming Scala implicit search engine is sort of a prover: • facts = implicit vals • rules = implicit defs
  • 23. Towers of Hanoi sealed trait Name case object Left extends Name case object Right extends Name case object Center extends Name trait Move[N <: Nat, L <: Name, R <: Name, C <: Name]
  • 24. Towers of Hanoi implicit def move0[L <: Name, R <: Name, C <: Name]: Move[_1, L, R, C] = new Move[_1, L, R, C] {}
  • 25. Towers of Hanoi implicit def move1[N <: Nat, M <: Nat, L <: Name, R <: Name, C <: Name] (implicit ev0 : LT[_1, N], ev1 : Diff.Aux[N, _1, M], ev2 : Move[M, L, C, R], ev3 : Move[_1, L, R, C], ev4 : Move[M, C, R, L]): Move[N, L, R, C] = new Move[N, L, R, C] {}
  • 26. Towers of Hanoi implicitly[Move[_3, Left.type, Right.type, Center.type]]
  • 27. Shapeless • So what are these Nat, LT, Diff.Aux things? • These are type-level numbers and arithmetical operations defined in a library called Shapeless: sealed trait Nat sealed trait _0 extends Nat sealed trait Succ[N <: Nat] extends Nat type _1 = Succ[_0] type _2 = Succ[_1] ... trait LT[A <: Nat, B <: Nat] object LT { def apply[A <: Nat, B <: Nat](implicit lt: A < B): LT[A, B] = lt type <[A <: Nat, B <: Nat] = LT[A, B] implicit def lt1[B <: Nat] = new <[_0, Succ[B]] {} implicit def lt2[A <: Nat, B <: Nat](implicit lt : A < B) = new <[Succ[A], Succ[B]] {} }
  • 28. Shapeless • HLists: like tuples, but with variable arity and collection functionality • (also can be created from case classes) • HMap: bidirectional map, e.g. HMap[BiMapIS](23 -> "foo", "bar" -> 13) • Coproducts: Like Either, but with arbitrary number of choices • Lens: compositional getters and setters for nested case classes • collections with statically known sizes • typesafe casting (wrapping in an Option)
  • 29. References • http://debasishg.blogspot.com/2010/02/scala-self-type-annotations-for.html • http://stackoverflow.com/questions/1154571/scala-abstract-types-vs-generics • http://like-a-boss.net/2013/03/29/polymorphism-and-typeclasses-in-scala.html • http://lanyrd.com/2014/scalaio-fr/sdgcwm • https://apocalisp.wordpress.com/2010/06/08/type-level-programming-in-scala • https://github.com/milessabin/shapeless/wiki/Feature-overview%3a-shapeless- 2.0.0