-
Notifications
You must be signed in to change notification settings - Fork 0
/
diWithReader.sc
71 lines (58 loc) · 1.85 KB
/
diWithReader.sc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
trait Travel
case class SimpleTravel(desde: String, hasta: String) extends Travel
trait Repository[A] {
def save(a: A): A
}
trait TravelRepository extends Repository[Travel]
object TravelRepositoryArangoDB extends TravelRepository {
def save(tr: Travel): Travel = {
println( "Here we could persist our data or send it further " + tr)
tr
}
}
trait TravelService {
def createTravelRequest(from: String,
to: String
): TravelRepository => Travel
}
// with simple function lifting
object TravelServiceImp extends TravelService {
def createTravelRequest(from: String,
to: String
): TravelRepository => Travel = {
tr => {
val aTravel = SimpleTravel(desde = from, hasta = to)
tr.save(aTravel)
}
}
}
case class Reader[R, A](run: R => A) {
def map[B](f: A => B): Reader[R, B] =
Reader(r => f(run(r)))
def flatMap[B](f: A => Reader[R, B]): Reader[R, B] =
Reader(r => f(run(r)).run(r))
}
trait TravelService {
def createTravelRequest(from: String,
to: String
): Reader[TravelRepository, Travel]
}
// with a Monad Reader
object TravelServiceImpReader extends TravelService {
def createTravelRequest(from: String,
to: String
): Reader[TravelRepository, Travel] = {
Reader(tr => {
tr.save(SimpleTravel(desde = from, hasta = to))
}
)
}
}
val misViajesDeSueno: Reader[TravelRepository, (Travel, Travel)] = for {
a <- TravelServiceImpReader.createTravelRequest("OpenSouthCode", "Cádiz")
b <- TravelServiceImpReader.createTravelRequest("Cádiz", "Granda")
} yield (a,b)
println(misViajesDeSueno.run)
val result: (Travel, Travel) = misViajesDeSueno.run(TravelRepositoryArangoDB)
println(result._1)
println(result._2)