Advertisement
Guest User

Untitled

a guest
Jul 18th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.01 KB | None | 0 0
  1. // (f --> g)(x) = f(g(x))
  2. infix operator --> : AdditionPrecedence
  3. func --> <A, B> (x: (A), f: (A) -> (B)) -> (B) {
  4.   return f(x)
  5. }
  6.  
  7. // (f --> g)(x) = f(g(x))
  8. func --> <A, B, C> (f: @escaping (A) -> (B), g: @escaping (B) -> C) -> (A) -> C {
  9.   return { g(f($0)) }
  10. }
  11.  
  12. func isEven(_ x: Int) -> Bool {
  13.   return x % 2 == 0
  14. }
  15.  
  16. func incr(_ x: Int) -> Int {
  17.   return x + 1
  18. }
  19.  
  20. func double(_ x: Int) -> Int {
  21.   return x * 2
  22. }
  23.  
  24. func append<T>(to accum: [T], with input: T) -> [T] {
  25.   return accum + [input]
  26. }
  27.  
  28. func mapping <A, B, C> (f: @escaping (A) -> (B)) -> (@escaping ((C, B) -> (C))) -> (C, A) -> (C) {
  29.   return { reducer in
  30.       return { accum, input in
  31.           reducer(accum, f(input))
  32.       }
  33.   }
  34. }
  35.  
  36. func filtering<A, C> (f: @escaping (A) -> (Bool)) -> (@escaping ((C, A) -> (C))) -> (C, A) -> (C) {
  37.   return { reducer in
  38.       return { accum, input in
  39.           if f(input) {
  40.               return reducer(accum, input)
  41.           } else {
  42.               return accum
  43.           }
  44.       }
  45.   }
  46. }
  47.  
  48. extension Collection {
  49.   typealias A = Iterator.Element
  50.  
  51.   func mmap<B>(_ f: @escaping (A) -> (B)) -> [B] {
  52.       return reduce([]) { accum, elem in
  53.           append(to: accum, with: f(elem))
  54.       }
  55.   }
  56.  
  57.   func mfilter(_ f: @escaping (A) -> (Bool)) -> [A] {
  58.       return reduce([]) { accum, elem in
  59.           if f(elem) {
  60.               return append(to: accum, with: elem)
  61.           } else {
  62.               return accum
  63.           }
  64.       }
  65.   }
  66. }
  67.  
  68. @inline(never)
  69. func testOldWay(input: [Int]) -> Int {
  70.     return input.map(incr).filter(isEven).reduce(0, (+))
  71. }
  72.  
  73. @inline(never)
  74. func testNewWay(input: [Int]) -> Int {
  75.     return input.reduce(0, mapping(f: incr)(filtering (f: isEven)(+)))
  76. }
  77.  
  78. @inline(never)
  79. func testImperative(input: [Int]) -> Int {
  80.     var res = 0
  81.     for i in input where i % 2 == 0 {
  82.         res += (i + 1)
  83.     }
  84.     return res
  85. }
  86.  
  87. print(testOldWay(input: Array(0...10)))
  88. print(testNewWay(input: Array(0...10)))
  89. print(testImperative(input: Array(0...10)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement