Skip to content

Commit

Permalink
Step 7: Create type class Flattener
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaparadela committed Nov 26, 2018
1 parent dbd4879 commit 669762a
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/main/scala/training/Program.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ object Program extends App {
case class Account(id: String, balance: Int)
case class Statement(isRich: Boolean, accounts: Int)

def getBalanceBank1: Maybe[Account] = Yes(Account("a1", 100))
def getBank1Credentials: Maybe[String] = Yes("MyUser_MyPassword")

def getBalanceBank1(credentials: String): Maybe[Account] = Yes(Account("a1", 100))

def getBalanceBank2: Maybe[Int] = Yes(80)

val moneyInPocket: Int = 20

val b1: Maybe[Int] = getBalanceBank1.map(_.balance)
val c: Maybe[String] = getBank1Credentials
val b1: Maybe[Int] = getBank1Credentials.flatMap(cred => getBalanceBank1(cred).map(_.balance))
val b2: Maybe[Int] = getBalanceBank2
val p: Maybe[Int] = moneyInPocket.pure

Expand Down
6 changes: 6 additions & 0 deletions src/main/scala/training/implicits.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ object implicits {

implicit def maybeLifter: Lifter[Maybe] = new MaybeLifter

implicit def maybeFlattener: Flattener[Maybe] = new MaybeFlattener

//Syntax

implicit class CombinatorSyntax[A](self: Maybe[A]) {
Expand All @@ -30,4 +32,8 @@ object implicits {
def pure[F[_]](implicit ev: Lifter[F]): F[A] = ev.pure(self)
}

implicit class FlattenerSyntax[A](self: Maybe[A])(implicit ev: Flattener[Maybe]){
def flatMap[B](f: A => Maybe[B]): Maybe[B] = ev.flatMap(self, f)
}

}
7 changes: 7 additions & 0 deletions src/main/scala/training/instances.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,12 @@ object instances {
override def pure[A](a: A): Maybe[A] = Maybe(a)
}

class MaybeFlattener extends Flattener[Maybe] {
override def flatMap[A, B](fa: Maybe[A], f: A => Maybe[B]): Maybe[B] = fa match {
case Yes(a) => f(a)
case No => No
}
}


}
4 changes: 4 additions & 0 deletions src/main/scala/training/typeclasses.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,9 @@ object typeclasses {
def pure[A](a: A): F[A]
}

trait Flattener[F[_]]{
def flatMap[A, B](fa: F[A], f: A => F[B]): F[B]
}


}

0 comments on commit 669762a

Please sign in to comment.