Created
March 29, 2019 09:45
-
-
Save chriseidhof/3c8349310728d7e5916b988bea8af7a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// Deforestation | |
// | |
// Created by Chris Eidhof on 29.03.19. | |
// Copyright © 2019 objc.io. All rights reserved. | |
// | |
import Foundation | |
struct Build<Element, Result> { | |
let empty: Result | |
let append: (inout Result, Element) -> () | |
} | |
struct Lazy<Element, Result> { | |
let force: (_ consumer: Build<Element, Result>) -> Result | |
func filter(_ cond: @escaping (Element) -> Bool) -> Lazy<Element, Result> { | |
return Lazy { consumer in | |
self.force(Build(empty: consumer.empty, append: { arr, el in | |
if cond(el) { | |
consumer.append(&arr, el) | |
} | |
})) | |
} | |
} | |
func map<B>(_ transform: @escaping (Element) -> B) -> Lazy<B, Result> { | |
return Lazy<B, Result> { consumer in | |
self.force(Build(empty: consumer.empty, append: { arr, el in | |
consumer.append(&arr, transform(el)) | |
})) | |
} | |
} | |
func reduce(_ initial: Result, _ combine: (inout Result, Element) -> ()) -> Result { | |
return withoutActuallyEscaping(combine) { comb in | |
force(Build(empty: initial, append: comb)) | |
} | |
} | |
} | |
extension Array { | |
func lazy<Result>() -> Lazy<Element, Result> { | |
return Lazy { witness in | |
var result = witness.empty | |
for i in self { | |
witness.append(&result, i) | |
} | |
return result | |
} | |
} | |
} | |
print([1,2,3].lazy().map({ $0 * 2}).filter { $0 != 0 }.reduce(0, +=)) | |
print([1,2,3].lazy().map({ $0 * 2}).filter { $0 != 0 }.reduce([], { $0.append($1) })) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment