13. val factory_: File => String => User =
file => name => readFromFile(name)
val factory: String => User = factory_(usersFile)
Look ma, no interfaces
13 WWW.TIKALK.COM
26. trait Future[A] {
def map[B](f: A => B): Future[B]
{
val user = findUser(userName)
val age: Future[Int] = user.map{user => user.age}
26 WWW.TIKALK.COM
27. val result = new ArrayList(list.size)
for (i <- 0 to (list.size - 1)) {
result += compute(list(i))
}
result
Vs.
list.map(compute)
27 WWW.TIKALK.COM
28. class ComputeTask extends RecursiveTask {
def compute = // split and call
invokeAll...
{
val pool = new ForkJoinPool()
val task = new ComputeTask()
pool.invoke(task)
Vs.
list.par.map(compute)
28 WWW.TIKALK.COM
29. trait Future[A] {
def get: A
def map[B](f: A => B) = new Future[B] {
def get = f(Future.this.get)
{
{
29 WWW.TIKALK.COM
30. def marry(man: User, woman: User): Family = â â â
val joe = findUser("joe")
val jane = findUser("jane")
Get Joe and Jane married
30 WWW.TIKALK.COM
31. Future[Family]
User => Family
joe.map{joe => jane.map{jane => marry(joe, jane)}}
User => Future[Family]
Future[Future[Family]]
31 WWW.TIKALK.COM
38. val marry: Future[User => User => Family] = Future(marry)
val partial: Future[User => Family] = futureMarry.apply(joe)
val family: Future[Family] = partial.apply(jane)
Future(marry).apply(joe).apply(jane)
Future(marry)(joe)(jane)
Using apply compiles iff A is a function
38 WWW.TIKALK.COM
51. Monoid
⢠For type A to be (have) a Monoid:
⢠Binary operation ââ˘â: (A, A) => A
⢠Identity element ââ â: A
51 WWW.TIKALK.COM
52. ⢠String is a Monoid (2 ways):
⢠Binary operation: append or prepend
⢠Identity element: ââ
⢠Int is a Monoid (2 ways):
⢠Binary operation: + or *
⢠Identity element: 0 or 1
52 WWW.TIKALK.COM
53. ⢠Future[A] is a monoid, if A is a monoid
⢠Binary operation: Future(A#â˘)
⢠(Future as applicative)
⢠Identity element: Future(A#identity)
53 WWW.TIKALK.COM
55. Folds: reduce values to
one
⢠List(x,y,z) => â ⢠x ⢠y ⢠z
⢠Option(x) => if Some â ⢠x
else â
55 WWW.TIKALK.COM
56. Unfolds: Create values
from initial value and
function
⢠1, if (a < 3) Some(a, a+1) else None
⢠Some(1, 2), Some(2, 3), None
⢠â â˘1â˘2â˘3
⢠If our monoid is a List:
⢠Nil ++ List(1) ++ List(2) ++ List(3)
⢠List(1,2,3)
56 WWW.TIKALK.COM
57. Since many things are
monoids, we can have
many generic algorithms
57 WWW.TIKALK.COM
58. Problems with subtyping:
⢠Namespace pollution
⢠Need to control the class
⢠Describes behavior, not âis-aâ
⢠Sometimes ability is conditional:
⢠Future is a monoid if A is a monoid
⢠Sometimes there are different definitions
⢠E.g., 2 monoids for integers
⢠Maybe a class has several facets
⢠E.g. context of 2 values
58 WWW.TIKALK.COM
59. Typeclass
⢠Define an API
⢠Create instance for each class that
can conform to the API
59 WWW.TIKALK.COM