Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object Main extends App {
- def identity[T](value: T): T = value
- trait Covariative[T] {
- def map[R](f: T => R): Covariative[R]
- }
- trait Contravariative[T] {
- def contraMap[R >: Null](f: R => T): Contravariative[R]
- }
- trait Invariative[T] {
- def invMap[R](f: T => R, g: R => T): Invariative[R]
- }
- class Box[T](var _value: T = null) extends Covariative[T]
- with Contravariative[T]
- with Invariative[T] {
- self =>
- def save(arg: T): Unit = _value = arg
- def get: T = _value
- def map[R](f: T => R): Box[R] = new Box(f(_value))
- def contraMap[R >: Null](g: R => T): Box[R] = new Box[R](null)
- {
- override def save(arg: R): Unit = self.save(g(arg))
- }
- def invMap[R](f: T => R, g: R => T): Box[R] = null
- }
- def testCovariative(): Unit = {
- println("***Testing Covariative Functor***")
- val box = new Box[Int](51)
- val toBinaryFunc: Int => String = Integer.toBinaryString
- val mappedBox = box map toBinaryFunc
- println("Example use value:" + mappedBox.get)
- val identityBox: Box[Int] = box map identity
- println("Pass Identity Rule:" + (identityBox.get == box.get))
- val squareFunc: Int => Int = (t) => t * t
- val squaredBinaryBox = box map (squareFunc andThen toBinaryFunc)
- println("Pass Composition Rule:" + (squaredBinaryBox.get == "101000101001"))
- }
- def testContravariative(): Unit = {
- println("\n***Testing Contravariative Functor***")
- val box = new Box[String]("ab")
- val parseFunc= (s:String)=>s.toLowerCase()
- val contraMappedBox = box contraMap parseFunc
- contraMappedBox.save("ABAB")
- println("Example use value:" + contraMappedBox.get)
- }
- def testInvariative(): Unit = {
- println("\n***Testing Invariative Functor***")
- }
- testCovariative()
- testContravariative()
- testInvariative()
- }
Add Comment
Please, Sign In to add comment