4. オブジェクト指向と
関数型の融合
Have the best of both worlds.
Construct elegant class hierarchies
for maximum code reuse and
extensibility, implement their behavior
using higher-order functions. Or
anything in-between.
— from http://www.scala-lang.org/
Object-Oriented Meets Functional
17. オブジェクト指向的コイン
case class OoCoin(private var head: Boolean) {
def flip() = { head = !head }
def stay() = {} // do nothing
def get = head
}
Object-Oriented Coin
18. オブジェクト指向的コイン
case class OoCoin(private var head: Boolean) {
def flip() = { head = !head }
def stay() = {} // do nothing
def get = head
}
var (variable) で宣言し
たフィールドに再代入
Object-Oriented Coin
19. val c = OoCoin(true)
c.flip()
c.stay()
c.flip()
println("Showing a head? " + c.get)
63. case class CoinAction[A](action: Coin => (Coin, A))
extends (Coin => (Coin, A)) {
def apply(c: Coin) = action(c)
def +[B](next: CoinAction[B]): CoinAction[B] =
flatMap(_ => next)
def map[B](f: A => B): CoinAction[B] = CoinAction { c0 =>
val (c1, a) = apply(c0)
(c1, f(a))
}
def flatMap[B](f: A => CoinAction[B]): CoinAction[B] =
CoinAction { c0 =>
val (c1, a) = apply(c0)
f(a)(c1)
}
}
64. case class CoinAction[A](action: Coin => (Coin, A))
extends (Coin => (Coin, A)) {
def apply(c: Coin) = action(c)
def +[B](next: CoinAction[B]): CoinAction[B] =
flatMap(_ => next)
def map[B](f: A => B): CoinAction[B] = CoinAction { c0 =>
val (c1, a) = apply(c0)
(c1, f(a))
}
def flatMap[B](f: A => CoinAction[B]): CoinAction[B] =
CoinAction { c0 =>
val (c1, a) = apply(c0)
f(a)(c1)
}
}
Coin のメソッドをどこ
からも呼び出してない
65. case class State[S, +A](run: S => (S, A)) {
def map[B](f: A => B): State[S, B] =
State { s =>
val (s2, a) = run(s)
(s2, f(a))
}
def flatMap[B](f: A => State[S, B]): State[S, B] =
State { s =>
val (s2, a) = run(s)
f(a).run(s2)
}
}
Coin を型パラメーター
S として抽象化
Functional Programming in Scala
http://www.manning.com/bjarnason/ より抜粋、一部改変
66. type CoinAction[A] = State[Coin, A]
val flip: CoinAction[Boolean] = State { c =>
val head = !c.head
(Coin(head), head)
}
val stay: CoinAction[Boolean] = State(c => (c, c.head))
CoinAction を type alias
として定義
70. Scalaz
Scalaz provides purely functional
data structures to complement those
from the Scala standard library.
— from http://typelevel.org/projects/scalaz/