Created
April 13, 2017 00:12
-
-
Save chriseidhof/98dac77679337dc9d6b0dc71aa9e6810 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
import UIKit | |
struct Monoid<A> { | |
let zero: A | |
let append: (A, A) -> A | |
} | |
let additive = Monoid(zero: 0, append: +) | |
let multiplicative = Monoid(zero: 1, append: *) | |
additive.append(5, 6) | |
extension Array { | |
func reduced(_ monoid: Monoid<Element>) -> Element { | |
return self.reduce(monoid.zero, monoid.append) | |
} | |
} | |
Array(1..<10).reduced(additive) | |
let conjuctiveBool = Monoid(zero: true, append: { $0 && $1 }) | |
let disjunctiveBool = Monoid(zero: false, append: { $0 || $1 }) | |
// FunctionM: (A) -> M | |
func functionMonoid<A, Result> (monoid: Monoid<Result>) -> Monoid<(A) -> Result> { | |
return Monoid(zero: { _ in monoid.zero }, append: { lhs, rhs in { a in monoid.append(lhs(a), rhs(a)) } }) | |
} | |
extension Array { | |
func and_filtered(predicates: [(Element) -> Bool]) -> [Element] { | |
return self.filter(predicates.reduced(functionMonoid(monoid: disjunctiveBool))) | |
} | |
} | |
let isEven = { $0 % 2 == 0 } | |
let isLessThan10 = { $0 < 10 } | |
Array(0...100).and_filtered(predicates: [isEven, isLessThan10]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment