SlideShare a Scribd company logo
1 of 30
Download to read offline
Scala Design Pattern



                 @xuwei_k
http://favstar.fm/users/yuroyoro/status/60285682958086145


                                   みんな

                                   Scalaのデザパタ

                                   しらない?
もう知らないとか言わせない(・ω・´)
            7-2章 Scalaのための
            デザインパターン

             ● 7-2-1 Loanパターン
             ● 7-2-2 CONCEPTパターン
             ● 7-2-3 Cakeパターン
             ● 7-2-4 バイナリメソッドへの対処
             ● 7-2-5 モナドパターンとfor内包表記
             ● 7-2-6 Generalized Type
               Constraints
             ● 7-2-7 Phantom Types
レビュー加わったぉ
             ● 7-2-8 型安全なBuilderパターン
             ● まとめ
みんなもちろん本持ってますよね?
Loanパターン

 ● 誰もが通る道
 ● 「Scala using」とかでググればたぶんいっぱい出てく
   る
 ● よって有名なので略(ぉぃ
 ● 自分が昔書いたもの↓

http://d.hatena.ne.jp/xuwei/20100917/1284734307
CONCEPTパターン
というより、自分でもどこからどこまでがCONSEPTなのかわかってないから、
  なんだかimplicit parameterの使用箇所の解説になってる・・・?(・ω・`)
突然ですが

● Haskellの型クラス(type classes)

● C++0xのConcept
入るかもしれなかったけど入らないことになっちゃった・・・(´・ω・`)



              知ってますか?
Odersky先生
        の論文

http://ropas.snu.
ac.
kr/~bruno/papers/
TypeClasses.pdf
1. Introduction
2. Type Classes in Haskell
     1. Single-parameter type classes
     2. Common extensions
3. Implicits
     1. Implicits in Scala
     2. Implicits as the missing link
4. The CONCEPT Pattern
     1. Concepts: type-class-style interfaces in OO
5. Applications and Comparison with Type Classes
     1. Ordering concept
     2. Abstract data types
     3. Statically-typed printf
     4. Type class programs are OO programs
1. Advanced Uses of Type Classes
    1. Associated types in GHC Haskell
    2. Implicits and type members
    3. Session types
    4. Arity-polymorphic ZipWith in Scala
    5. ZipWith using prioritised overlapping implicits
    6. Encoding generalized constraints
    7. Type theories using implicits
2. Discussion and Related Work
    1. Real-world applications
    2. Type classes, JavaGI and concepts
    3. Generic programming in the large
3. Conclusion
6.6 Encoding generalized constraint

sealed abstract class <:< [-S,+T ] extends (S => T)

implicit def conforms [A]: A <:< A = new (A <:< A) {
def apply (x : A) = x
}

trait Traversable[T ] {
type Coll[X ]
def atten [U ] (implicit w : T <:< Traversable[U ]): Coll[U ]
}
なんかすごそう Σ(・д・;)
みずしまさんのblog
http://d.hatena.ne.
jp/kmizushima/20110615/1308142330

(難しくみせないようにわざとCONSEPTって言葉だしてないけど)


これある意味CONSEPTパターンの
説明してる?
代表的な物

● scala.math.Equiv
● scala.math.PartialOrdering
● scala.math.Ordering
● scala.math.Numeric
● scala.math.Fractional
● scala.math.Integral

                  ここからちょっと数学っぽいお話・・・
Equiv (数学的な意味での)同値関係
scaladocをコピペ


 ● A trait for representing equivalence relations. It is
   important to distinguish between a type that can be
   compared for equality or equivalence and a
   representation of equivalence on some type. This trait is
   for representing the latter.

 ● An equivalence relation is a binary relation on a type.
   This relation is exposed as the equiv method of
   the Equiv trait. The relation must be

                                 http://en.wikipedia.org/wiki/Equivalence_relation
                                               http://ja.wikipedia.org/wiki/同値関係
               http://www.scala-lang.org/api/current/index.html#scala.math.Equiv
Equiv
1 reflexive: 反射律
equiv(x, x) == true for any x of type T.
2 symmetric: 対称律
equiv(x, y) == equiv(y, x) for any x and y of type T.
3 transitive: 推移律
if equiv(x, y) == true and equiv(y, z) == true,
then equiv(x, z) == true for any x, y, and z of type T
Ordering 順序付け可能な集合(?)
● A trait for representing total orderings. It is important to
  distinguish between a type that has a total order and a
  representation of total ordering on some type. This trait
  is for the latter.
● A ordering is a binary relation on a type T that is also an
  equivalence relation and partial ordering on values of
  type T. This relation is exposed as the compare method
  of the Ordering trait.

                               http://en.wikipedia.org/wiki/Total_order
                                   http://ja.wikipedia.org/wiki/順序集合
http://www.scala-lang.org/api/current/index.html#scala.math.Ordering
Ordering
This relation must be:
  ● reflexive: 反射律
x == x
  ● antisymmetric: 推移律
if x <= y && y <= x, then x == y
  ● transitive: 反対称律
if x <= y && y <= z, then x <= z
PartialOrdering
 ● A trait for representing partial orderings. It is important
   to distinguish between a type that has a partial order
   and a representation of partial ordering on some type.
   This trait is for representing the latter.
 ● A partial ordering is a binary relation on a type T that is
   also an equivalence relation on values of type T. This
   relation is exposed as the lteqmethod of
   the PartialOrdering trait.




http://en.wikipedia.org/wiki/Partial_order
PartialOrdering
This relation must be:
   ● reflexive:反射律
lteq(x, x) == true, for any x of type T.
   ● anti-symmetric:反対称律
lteq(x, y) == true and lteq(y, x) == true
then equiv(x, y), for any x and y of type T.
   ● transitive:推移律
if lteq(x, y) == true and lteq(y, z) == true
then lteq(x, z) == true,
for any x, y, and z of type T.
Numeric 数値
Scaladoc何も書いてないェ・・・

抽象メソッド達↓

def plus(x: T, y: T): T
def minus(x: T, y: T): T
def times(x: T, y: T): T
def negate(x: T): T
def fromInt(x: Int): T
def toInt(x: T): Int
def toLong(x: T): Long
def toFloat(x: T): Float
def toDouble(x: T): Double
Ordering独自に定義してごにょごにょしてみる

https://gist.github.com/1047689
def sorted [B >: A] (implicit ord: Ordering[B]): List[A]
abstract sealed case class Language(year:Int,name:String)

object Scala extends Language(2003,"Scala")
object Java extends Language(1995,"Java")
object Clojure extends Language(2007,"Clojure")
object D extends Language(1999,"D")

val languages = List(Java,Scala,Clojure,D)
/** 名前の長さ順 */
implicit val nameLengthOrdering = new Ordering[Language]{
def compare(x: Language, y: Language) =
x.name.length compare y.name.length
}



languages.sorted



List(Language(1999,D), Language(1995,Java), Language(2003,
Scala), Language(2007,Clojure))
/** 誕生年順 */
implicit val yearOrdering = new Ordering[Language]{
def compare(x: Language, y: Language) =
x.year compare y.year
}

language.sorted

List(Language(1995,Java), Language(1999,D),
Language(2003,Scala), Language(2007,Clojure))
/** 辞書順 */
implicit val nameOrdering = new Ordering[Language]{
def compare(x: Language, y: Language) = x.name compare y.name
}

languages.sorted

List(Language(2007,Clojure), Language(1999,D), Language(1995,
Java), Language(2003,Scala))


//Oderingにreverseってメソッドがあるので、明示的に渡して逆順にしてみたり
languages.sorted(nameOrdering.reverse)

List(Language(2003,Scala), Language(1995,Java), Language(1999,
D), Language(2007,Clojure))
その他いろいろ( Listの場合 )

def sum [B >: A] (implicit num: Numeric[B]): B

def toMap [T, U] (implicit ev: <:<[A, (T, U)]): Map[T, U]

def unzip [A1, A2] (implicit asPair: (A) ⇒ (A1, A2)): (List[A1], List[A2])

def unzip3 [A1, A2, A3] (implicit asTriple: (A) ⇒ (A1, A2, A3)): (List[A1],List[A2], List[A3])

def flatten [B] (implicit asTraversable: (A) ⇒ TraversableOnce[B]): Traversable[B]

def max [B >: A] (implicit cmp: Ordering[B]): A

def maxBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A

def min [B >: A] (implicit cmp: Ordering[B]): A

def minBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A

def product [B >: A] (implicit num: Numeric[B]): B

defsortBy [B] (f: (A) ⇒ B)(implicit ord: Ordering[B]): List[A]
全部のデザパタ説明できなかったので
その他のものは

● 本読みましょう
● 誰か次回(?)発表して
おわり?

質問タイム?

More Related Content

What's hot

Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operatorsNico Ludwig
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in JavaMudit Gupta
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 

What's hot (17)

Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala
ScalaScala
Scala
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Java best practices
Java best practicesJava best practices
Java best practices
 
(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
scala
scalascala
scala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 

Viewers also liked

rpscala35-scala2.9.0
rpscala35-scala2.9.0rpscala35-scala2.9.0
rpscala35-scala2.9.0Kenji Yoshida
 
Sns suite presentation
Sns suite presentationSns suite presentation
Sns suite presentationJason Namkung
 
20120718 scalaで転職
20120718 scalaで転職20120718 scalaで転職
20120718 scalaで転職大翼 福田
 
sbt 0.10 for beginners?
sbt 0.10 for beginners?sbt 0.10 for beginners?
sbt 0.10 for beginners?k4200
 
Lifthub (rpscala #31)
Lifthub (rpscala #31)Lifthub (rpscala #31)
Lifthub (rpscala #31)k4200
 
Real-Time 3D Programming in Scala
Real-Time 3D Programming in ScalaReal-Time 3D Programming in Scala
Real-Time 3D Programming in ScalaHideyuki Takeuchi
 
私とScalaと2010 @hito_asa
私とScalaと2010 @hito_asa私とScalaと2010 @hito_asa
私とScalaと2010 @hito_asaHitoshi Asai
 
Scala勉強会 in 渋谷 2010→2011(鹿島)
Scala勉強会 in 渋谷 2010→2011(鹿島)Scala勉強会 in 渋谷 2010→2011(鹿島)
Scala勉強会 in 渋谷 2010→2011(鹿島)k4200
 
Lifthub (#rpscala 26)
Lifthub (#rpscala 26)Lifthub (#rpscala 26)
Lifthub (#rpscala 26)k4200
 
Grass
GrassGrass
Grassk4200
 
ScalaのソースをEclipseでビルドしてみた
ScalaのソースをEclipseでビルドしてみたScalaのソースをEclipseでビルドしてみた
ScalaのソースをEclipseでビルドしてみたKota Mizushima
 
トピックモデルの評価指標 Perplexity とは何なのか?
トピックモデルの評価指標 Perplexity とは何なのか?トピックモデルの評価指標 Perplexity とは何なのか?
トピックモデルの評価指標 Perplexity とは何なのか?hoxo_m
 

Viewers also liked (17)

rpscala35-scala2.9.0
rpscala35-scala2.9.0rpscala35-scala2.9.0
rpscala35-scala2.9.0
 
scala-kaigi1-sbt
scala-kaigi1-sbtscala-kaigi1-sbt
scala-kaigi1-sbt
 
Sns suite presentation
Sns suite presentationSns suite presentation
Sns suite presentation
 
Rpscala18th
Rpscala18thRpscala18th
Rpscala18th
 
20120718 scalaで転職
20120718 scalaで転職20120718 scalaで転職
20120718 scalaで転職
 
sbt 0.10 for beginners?
sbt 0.10 for beginners?sbt 0.10 for beginners?
sbt 0.10 for beginners?
 
Lifthub (rpscala #31)
Lifthub (rpscala #31)Lifthub (rpscala #31)
Lifthub (rpscala #31)
 
Real-Time 3D Programming in Scala
Real-Time 3D Programming in ScalaReal-Time 3D Programming in Scala
Real-Time 3D Programming in Scala
 
Scala lang evolution
Scala lang evolutionScala lang evolution
Scala lang evolution
 
私とScalaと2010 @hito_asa
私とScalaと2010 @hito_asa私とScalaと2010 @hito_asa
私とScalaと2010 @hito_asa
 
Scala勉強会 in 渋谷 2010→2011(鹿島)
Scala勉強会 in 渋谷 2010→2011(鹿島)Scala勉強会 in 渋谷 2010→2011(鹿島)
Scala勉強会 in 渋谷 2010→2011(鹿島)
 
Lifthub (#rpscala 26)
Lifthub (#rpscala 26)Lifthub (#rpscala 26)
Lifthub (#rpscala 26)
 
Rpscala2011 0601
Rpscala2011 0601Rpscala2011 0601
Rpscala2011 0601
 
Scala repl
Scala replScala repl
Scala repl
 
Grass
GrassGrass
Grass
 
ScalaのソースをEclipseでビルドしてみた
ScalaのソースをEclipseでビルドしてみたScalaのソースをEclipseでビルドしてみた
ScalaのソースをEclipseでビルドしてみた
 
トピックモデルの評価指標 Perplexity とは何なのか?
トピックモデルの評価指標 Perplexity とは何なのか?トピックモデルの評価指標 Perplexity とは何なのか?
トピックモデルの評価指標 Perplexity とは何なのか?
 

Similar to Scala design pattern

BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
IntroductiontoprogramminginscalaAmuhinda Hungai
 
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
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scaladatamantra
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsMiles Sabin
 
Core Java Programming Language (JSE) : Chapter III - Identifiers, Keywords, ...
Core Java Programming Language (JSE) : Chapter III -  Identifiers, Keywords, ...Core Java Programming Language (JSE) : Chapter III -  Identifiers, Keywords, ...
Core Java Programming Language (JSE) : Chapter III - Identifiers, Keywords, ...WebStackAcademy
 
Slides:Coercion Quantification
Slides:Coercion QuantificationSlides:Coercion Quantification
Slides:Coercion QuantificationNingningXIE1
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About MorphismsUberto Barbini
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanJimin Hsieh
 

Similar to Scala design pattern (20)

BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
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
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to Dotty
 
Core Java Programming Language (JSE) : Chapter III - Identifiers, Keywords, ...
Core Java Programming Language (JSE) : Chapter III -  Identifiers, Keywords, ...Core Java Programming Language (JSE) : Chapter III -  Identifiers, Keywords, ...
Core Java Programming Language (JSE) : Chapter III - Identifiers, Keywords, ...
 
Slides:Coercion Quantification
Slides:Coercion QuantificationSlides:Coercion Quantification
Slides:Coercion Quantification
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About Morphisms
 
Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
 
Yes scala can!
Yes scala can!Yes scala can!
Yes scala can!
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
scala.ppt
scala.pptscala.ppt
scala.ppt
 
Scala
ScalaScala
Scala
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 

Recently uploaded (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

Scala design pattern

  • 2. http://favstar.fm/users/yuroyoro/status/60285682958086145 みんな Scalaのデザパタ しらない?
  • 3. もう知らないとか言わせない(・ω・´) 7-2章 Scalaのための デザインパターン ● 7-2-1 Loanパターン ● 7-2-2 CONCEPTパターン ● 7-2-3 Cakeパターン ● 7-2-4 バイナリメソッドへの対処 ● 7-2-5 モナドパターンとfor内包表記 ● 7-2-6 Generalized Type Constraints ● 7-2-7 Phantom Types レビュー加わったぉ ● 7-2-8 型安全なBuilderパターン ● まとめ
  • 5. Loanパターン ● 誰もが通る道 ● 「Scala using」とかでググればたぶんいっぱい出てく る ● よって有名なので略(ぉぃ ● 自分が昔書いたもの↓ http://d.hatena.ne.jp/xuwei/20100917/1284734307
  • 7. 突然ですが ● Haskellの型クラス(type classes) ● C++0xのConcept 入るかもしれなかったけど入らないことになっちゃった・・・(´・ω・`) 知ってますか?
  • 8. Odersky先生 の論文 http://ropas.snu. ac. kr/~bruno/papers/ TypeClasses.pdf
  • 9. 1. Introduction 2. Type Classes in Haskell 1. Single-parameter type classes 2. Common extensions 3. Implicits 1. Implicits in Scala 2. Implicits as the missing link 4. The CONCEPT Pattern 1. Concepts: type-class-style interfaces in OO 5. Applications and Comparison with Type Classes 1. Ordering concept 2. Abstract data types 3. Statically-typed printf 4. Type class programs are OO programs
  • 10. 1. Advanced Uses of Type Classes 1. Associated types in GHC Haskell 2. Implicits and type members 3. Session types 4. Arity-polymorphic ZipWith in Scala 5. ZipWith using prioritised overlapping implicits 6. Encoding generalized constraints 7. Type theories using implicits 2. Discussion and Related Work 1. Real-world applications 2. Type classes, JavaGI and concepts 3. Generic programming in the large 3. Conclusion
  • 11. 6.6 Encoding generalized constraint sealed abstract class <:< [-S,+T ] extends (S => T) implicit def conforms [A]: A <:< A = new (A <:< A) { def apply (x : A) = x } trait Traversable[T ] { type Coll[X ] def atten [U ] (implicit w : T <:< Traversable[U ]): Coll[U ] }
  • 14. 代表的な物 ● scala.math.Equiv ● scala.math.PartialOrdering ● scala.math.Ordering ● scala.math.Numeric ● scala.math.Fractional ● scala.math.Integral ここからちょっと数学っぽいお話・・・
  • 15. Equiv (数学的な意味での)同値関係 scaladocをコピペ ● A trait for representing equivalence relations. It is important to distinguish between a type that can be compared for equality or equivalence and a representation of equivalence on some type. This trait is for representing the latter. ● An equivalence relation is a binary relation on a type. This relation is exposed as the equiv method of the Equiv trait. The relation must be http://en.wikipedia.org/wiki/Equivalence_relation http://ja.wikipedia.org/wiki/同値関係 http://www.scala-lang.org/api/current/index.html#scala.math.Equiv
  • 16. Equiv 1 reflexive: 反射律 equiv(x, x) == true for any x of type T. 2 symmetric: 対称律 equiv(x, y) == equiv(y, x) for any x and y of type T. 3 transitive: 推移律 if equiv(x, y) == true and equiv(y, z) == true, then equiv(x, z) == true for any x, y, and z of type T
  • 17. Ordering 順序付け可能な集合(?) ● A trait for representing total orderings. It is important to distinguish between a type that has a total order and a representation of total ordering on some type. This trait is for the latter. ● A ordering is a binary relation on a type T that is also an equivalence relation and partial ordering on values of type T. This relation is exposed as the compare method of the Ordering trait. http://en.wikipedia.org/wiki/Total_order http://ja.wikipedia.org/wiki/順序集合 http://www.scala-lang.org/api/current/index.html#scala.math.Ordering
  • 18. Ordering This relation must be: ● reflexive: 反射律 x == x ● antisymmetric: 推移律 if x <= y && y <= x, then x == y ● transitive: 反対称律 if x <= y && y <= z, then x <= z
  • 19. PartialOrdering ● A trait for representing partial orderings. It is important to distinguish between a type that has a partial order and a representation of partial ordering on some type. This trait is for representing the latter. ● A partial ordering is a binary relation on a type T that is also an equivalence relation on values of type T. This relation is exposed as the lteqmethod of the PartialOrdering trait. http://en.wikipedia.org/wiki/Partial_order
  • 20. PartialOrdering This relation must be: ● reflexive:反射律 lteq(x, x) == true, for any x of type T. ● anti-symmetric:反対称律 lteq(x, y) == true and lteq(y, x) == true then equiv(x, y), for any x and y of type T. ● transitive:推移律 if lteq(x, y) == true and lteq(y, z) == true then lteq(x, z) == true, for any x, y, and z of type T.
  • 21. Numeric 数値 Scaladoc何も書いてないェ・・・ 抽象メソッド達↓ def plus(x: T, y: T): T def minus(x: T, y: T): T def times(x: T, y: T): T def negate(x: T): T def fromInt(x: Int): T def toInt(x: T): Int def toLong(x: T): Long def toFloat(x: T): Float def toDouble(x: T): Double
  • 23. def sorted [B >: A] (implicit ord: Ordering[B]): List[A]
  • 24. abstract sealed case class Language(year:Int,name:String) object Scala extends Language(2003,"Scala") object Java extends Language(1995,"Java") object Clojure extends Language(2007,"Clojure") object D extends Language(1999,"D") val languages = List(Java,Scala,Clojure,D)
  • 25. /** 名前の長さ順 */ implicit val nameLengthOrdering = new Ordering[Language]{ def compare(x: Language, y: Language) = x.name.length compare y.name.length } languages.sorted List(Language(1999,D), Language(1995,Java), Language(2003, Scala), Language(2007,Clojure))
  • 26. /** 誕生年順 */ implicit val yearOrdering = new Ordering[Language]{ def compare(x: Language, y: Language) = x.year compare y.year } language.sorted List(Language(1995,Java), Language(1999,D), Language(2003,Scala), Language(2007,Clojure))
  • 27. /** 辞書順 */ implicit val nameOrdering = new Ordering[Language]{ def compare(x: Language, y: Language) = x.name compare y.name } languages.sorted List(Language(2007,Clojure), Language(1999,D), Language(1995, Java), Language(2003,Scala)) //Oderingにreverseってメソッドがあるので、明示的に渡して逆順にしてみたり languages.sorted(nameOrdering.reverse) List(Language(2003,Scala), Language(1995,Java), Language(1999, D), Language(2007,Clojure))
  • 28. その他いろいろ( Listの場合 ) def sum [B >: A] (implicit num: Numeric[B]): B def toMap [T, U] (implicit ev: <:<[A, (T, U)]): Map[T, U] def unzip [A1, A2] (implicit asPair: (A) ⇒ (A1, A2)): (List[A1], List[A2]) def unzip3 [A1, A2, A3] (implicit asTriple: (A) ⇒ (A1, A2, A3)): (List[A1],List[A2], List[A3]) def flatten [B] (implicit asTraversable: (A) ⇒ TraversableOnce[B]): Traversable[B] def max [B >: A] (implicit cmp: Ordering[B]): A def maxBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A def min [B >: A] (implicit cmp: Ordering[B]): A def minBy [B] (f: (A) ⇒ B)(implicit cmp: Ordering[B]): A def product [B >: A] (implicit num: Numeric[B]): B defsortBy [B] (f: (A) ⇒ B)(implicit ord: Ordering[B]): List[A]