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 Closures
Sandip Kumar
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
Chikugehlot
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi 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.0
Kenji Yoshida
 
Sns suite presentation
Sns suite presentationSns suite presentation
Sns suite presentation
Jason Namkung
 
sbt 0.10 for beginners?
sbt 0.10 for beginners?sbt 0.10 for beginners?
sbt 0.10 for beginners?
k4200
 
Real-Time 3D Programming in Scala
Real-Time 3D Programming in ScalaReal-Time 3D Programming in Scala
Real-Time 3D Programming in Scala
Hideyuki Takeuchi
 
私とScalaと2010 @hito_asa
私とScalaと2010 @hito_asa私とScalaと2010 @hito_asa
私とScalaと2010 @hito_asa
Hitoshi Asai
 
Grass
GrassGrass
Grass
k4200
 
ScalaのソースをEclipseでビルドしてみた
ScalaのソースをEclipseでビルドしてみたScalaのソースをEclipseでビルドしてみた
ScalaのソースをEclipseでビルドしてみた
Kota Mizushima
 

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 Developers
Miles 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 Developers
Skills Matter
 
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
Miles Sabin
 

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

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

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]