Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created March 29, 2019 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/3c8349310728d7e5916b988bea8af7a3 to your computer and use it in GitHub Desktop.
Save chriseidhof/3c8349310728d7e5916b988bea8af7a3 to your computer and use it in GitHub Desktop.
//
// 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