Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // (f --> g)(x) = f(g(x))
- infix operator --> : AdditionPrecedence
- func --> <A, B> (x: (A), f: (A) -> (B)) -> (B) {
- return f(x)
- }
- // (f --> g)(x) = f(g(x))
- func --> <A, B, C> (f: @escaping (A) -> (B), g: @escaping (B) -> C) -> (A) -> C {
- return { g(f($0)) }
- }
- func isEven(_ x: Int) -> Bool {
- return x % 2 == 0
- }
- func incr(_ x: Int) -> Int {
- return x + 1
- }
- func double(_ x: Int) -> Int {
- return x * 2
- }
- func append<T>(to accum: [T], with input: T) -> [T] {
- return accum + [input]
- }
- func mapping <A, B, C> (f: @escaping (A) -> (B)) -> (@escaping ((C, B) -> (C))) -> (C, A) -> (C) {
- return { reducer in
- return { accum, input in
- reducer(accum, f(input))
- }
- }
- }
- func filtering<A, C> (f: @escaping (A) -> (Bool)) -> (@escaping ((C, A) -> (C))) -> (C, A) -> (C) {
- return { reducer in
- return { accum, input in
- if f(input) {
- return reducer(accum, input)
- } else {
- return accum
- }
- }
- }
- }
- extension Collection {
- typealias A = Iterator.Element
- func mmap<B>(_ f: @escaping (A) -> (B)) -> [B] {
- return reduce([]) { accum, elem in
- append(to: accum, with: f(elem))
- }
- }
- func mfilter(_ f: @escaping (A) -> (Bool)) -> [A] {
- return reduce([]) { accum, elem in
- if f(elem) {
- return append(to: accum, with: elem)
- } else {
- return accum
- }
- }
- }
- }
- @inline(never)
- func testOldWay(input: [Int]) -> Int {
- return input.map(incr).filter(isEven).reduce(0, (+))
- }
- @inline(never)
- func testNewWay(input: [Int]) -> Int {
- return input.reduce(0, mapping(f: incr)(filtering (f: isEven)(+)))
- }
- @inline(never)
- func testImperative(input: [Int]) -> Int {
- var res = 0
- for i in input where i % 2 == 0 {
- res += (i + 1)
- }
- return res
- }
- print(testOldWay(input: Array(0...10)))
- print(testNewWay(input: Array(0...10)))
- print(testImperative(input: Array(0...10)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement