Skip to content

Commit

Permalink
Step 2: Create type class Combinator
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaparadela committed Nov 25, 2018
1 parent 9dc4a61 commit b81c78d
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/main/scala/training/Program.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package training

import training.datatypes._
import training.implicits._

object Program extends App {

Expand All @@ -13,7 +14,7 @@ object Program extends App {
val b1: Maybe[Int] = getBalanceBank1
val b2: Maybe[Int] = getBalanceBank2

b1 + b2 //It will fail
maybeCombinator.combine(b1, b2)
}


Expand Down
7 changes: 7 additions & 0 deletions src/main/scala/training/implicits.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package training

import training.datatypes._
import training.instances._
import training.typeclasses._

object implicits {

implicit def intCombinator: Combinator[Int] = new IntCombinator

implicit def maybeCombinator[A](implicit CA: Combinator[A]): Combinator[Maybe[A]] = new MaybeCombinator[A]

}
18 changes: 18 additions & 0 deletions src/main/scala/training/instances.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
package training

import training.datatypes._
import training.typeclasses._

object instances {

class IntCombinator extends Combinator[Int] {
override def combine(x: Int, y: Int): Int = x + y
}

class MaybeCombinator[A](implicit CA: Combinator[A]) extends Combinator[Maybe[A]] {

override def combine(x: Maybe[A], y: Maybe[A]): Maybe[A] = (x, y) match {
case (No, No) => No
case (No, Yes(yy)) => y
case (Yes(xx), No) => x
case (Yes(xx), Yes(yy)) => Yes(CA.combine(xx, yy))
}

}


}
4 changes: 4 additions & 0 deletions src/main/scala/training/typeclasses.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@ package training

object typeclasses {

trait Combinator[A] {
def combine(x: A, y: A): A
}


}

0 comments on commit b81c78d

Please sign in to comment.