Guest User

Untitled

a guest
May 26th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. object Test {
  2. def curry[A,B,C](f: (A, B) => C): A => (B => C) = a => f(a, _)
  3. def uncurry[A,B,C](f: A => B => C): (A, B) => C = f(_)(_)
  4. def compose[A,B,C](f: B => C, g: A => B): A => C = a => f(g(a))
  5.  
  6. def mul(a:Int, b:Int) = a * b
  7. val mulC = curry(mul)
  8.  
  9. mulC(5)(10)
  10.  
  11.  
  12. // every func is a closure actually! (that's why curry works)
  13. // u can define anything anywhere
  14. // class in def/ def in class w/e
  15. // partially applied functions
  16. // simple for
  17. // case
  18. // no operators -> just functions
  19. // infix operator, postfix operator
  20. // () = {}
  21. // var/while/return []
  22. // class/object/apply/type params/override?
  23. // type
  24. // trait and dynamic classes (in case of Function1/2)
  25. // DSL homework:
  26.  
  27. class Pair[A,B](val first:A, val second:B) {
  28. override def toString: String = s"($first,$second)" // string context, we can write our own
  29. def applied[C](f: (A,B) => C):C = f(first, second)
  30. def swap:Pair[B,A] = Pair(second, first)
  31. }
  32.  
  33. object Pair {
  34. def apply[A,B](first:A, second:B):Pair[A,B] = new Pair(first, second)
  35. }
  36.  
  37. type Point = Pair[Int, Int] // type aliases
  38. type Rect = Pair[Point, Point] // type aliases, can be parametrized as well
  39.  
  40.  
  41. val topLeft = Pair(10, 20)
  42. val bottomRight = Pair(30, 40)
  43.  
  44. val rectangle = Pair(topLeft, bottomRight)
  45.  
  46. implicit class PairOps[A](first:A) {
  47. def x[B](second:B):Pair[A,B] = Pair(first, second)
  48. }
  49.  
  50. val rect:Rect = (0 x 0) x (3 x 4)
  51.  
  52. rect.first
  53. rect.second
  54.  
  55. rect.swap
  56.  
  57.  
  58. def dist(p1:Point, p2:Point):Double = Math.sqrt(
  59. Math.pow(p1.first - p2.first, 2) + Math.pow(p1.second - p2.second, 2)
  60. )
  61.  
  62. (rect applied dist) == 5.0
  63.  
  64. implicit class Func2Ops[A,B,C](f: (A,B) => C) {
  65. def paired: Pair[A,B] => C = p => f(p.first, p.second)
  66. def applyPair(p:Pair[A,B]):C = f(p.first, p.second)
  67. }
  68.  
  69. (dist _) applyPair rect
  70.  
  71.  
  72.  
  73. // home work:
  74. def trim(s:String) = s.trim
  75. def upperCase(s:String) = s.toUpperCase
  76. def surround(dec:String) = (s:String) => dec + s + dec
  77.  
  78. val result = (
  79. Wrap function trim
  80. chainWith upperCase
  81. andChainWith surround("+++")
  82. runWith " HeLlo "
  83. )
  84.  
  85. result == "+++HELLO++"
  86. }
Add Comment
Please, Sign In to add comment