Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import Foundation
  2.  
  3. // High Order Function: Implementing Map, Filter, Reduce
  4. /* Map */
  5.  
  6. func Map<T, U>(_ seq: [T], transform: ((T) -> U)) -> [U] { return seq.map { transform($0) } }
  7. //func Map<T, U>(_ seq: [T], transform: ((T) -> U)) -> [U] where T: Equatable, U: Equatable {
  8. // var result = [U]()
  9. // for f1 in seq { result.append(transform(f1)) }
  10. //
  11. // return result
  12. //}
  13.  
  14. let mRes = Map([1,2,3]) { String($0) }
  15. mRes
  16.  
  17.  
  18. func Filter<T>(_ seq: [T], predicate: ((T) -> Bool)) -> [T] { return seq.filter { predicate($0) } }
  19. //func Filter<T>(_ seq: [T], predicate: ((T) -> Bool)) -> [T] {
  20. // var res: [T] = []
  21. // for f1 in seq {
  22. // if predicate(f1) {
  23. // res.append(f1)
  24. // }
  25. // }
  26. // return res
  27. //}
  28.  
  29. let fRes = Filter([1,2,3]) { $0 % 2 != 0 }
  30. fRes
  31.  
  32.  
  33. let res = [1,2,3].reduce(0) { $0 + $1 }
  34. res
  35.  
  36. // Reduce
  37. func Reduce<T, U>(_ seq: [T], initValue: U, reduce: ((U, T) -> U)) -> U {
  38. var result = initValue
  39. for f1 in seq {
  40. result = reduce(result, f1)
  41. }
  42. return result
  43. }
  44.  
  45. let rRes = Reduce([1,2,3], initValue: 0) { $0 + $1 }
  46. rRes
  47.  
  48.  
  49.  
  50. //////
  51. func onePlus(_ arr: [Int]) -> [String] {
  52. var input = [String]()
  53.  
  54. for x in arr {
  55. input.append(String(x + 1))
  56. }
  57. return input
  58. }
  59.  
  60. let oRes = onePlus([1,2,3])
  61. oRes
  62.  
  63. func DumbMap(_ source: [Int], transform: ((Int) -> Int)) -> [Int] {
  64. var ret: [Int] = []
  65. for f1 in source {
  66. ret.append(transform(f1))
  67. }
  68. return ret
  69. }
  70.  
  71. let dRes = DumbMap([1,2,3], transform: { $0 + 1 })
  72. dRes
  73.  
  74. func SmartMap<T, U>(_ seq: [T], transform: ((T) -> U)) -> [U] { return seq.map { transform($0) } }
  75. let sRes = SmartMap([1,2,3]) { String($0 + 1) }
  76. sRes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement