Guest User

Untitled

a guest
Nov 24th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. object Main extends App {
  2. def identity[T](value: T): T = value
  3.  
  4. trait Covariative[T] {
  5. def map[R](f: T => R): Covariative[R]
  6. }
  7.  
  8. trait Contravariative[T] {
  9. def contraMap[R >: Null](f: R => T): Contravariative[R]
  10. }
  11.  
  12. trait Invariative[T] {
  13. def invMap[R](f: T => R, g: R => T): Invariative[R]
  14. }
  15.  
  16. class Box[T](var _value: T = null) extends Covariative[T]
  17. with Contravariative[T]
  18. with Invariative[T] {
  19. self =>
  20.  
  21. def save(arg: T): Unit = _value = arg
  22.  
  23. def get: T = _value
  24.  
  25. def map[R](f: T => R): Box[R] = new Box(f(_value))
  26.  
  27. def contraMap[R >: Null](g: R => T): Box[R] = new Box[R](null)
  28. {
  29. override def save(arg: R): Unit = self.save(g(arg))
  30. }
  31.  
  32. def invMap[R](f: T => R, g: R => T): Box[R] = null
  33. }
  34.  
  35. def testCovariative(): Unit = {
  36. println("***Testing Covariative Functor***")
  37.  
  38. val box = new Box[Int](51)
  39. val toBinaryFunc: Int => String = Integer.toBinaryString
  40.  
  41. val mappedBox = box map toBinaryFunc
  42. println("Example use value:" + mappedBox.get)
  43.  
  44. val identityBox: Box[Int] = box map identity
  45. println("Pass Identity Rule:" + (identityBox.get == box.get))
  46.  
  47. val squareFunc: Int => Int = (t) => t * t
  48. val squaredBinaryBox = box map (squareFunc andThen toBinaryFunc)
  49. println("Pass Composition Rule:" + (squaredBinaryBox.get == "101000101001"))
  50. }
  51.  
  52. def testContravariative(): Unit = {
  53. println("\n***Testing Contravariative Functor***")
  54.  
  55. val box = new Box[String]("ab")
  56. val parseFunc= (s:String)=>s.toLowerCase()
  57.  
  58. val contraMappedBox = box contraMap parseFunc
  59. contraMappedBox.save("ABAB")
  60. println("Example use value:" + contraMappedBox.get)
  61. }
  62.  
  63. def testInvariative(): Unit = {
  64. println("\n***Testing Invariative Functor***")
  65. }
  66.  
  67. testCovariative()
  68. testContravariative()
  69. testInvariative()
  70. }
Add Comment
Please, Sign In to add comment