Created
September 28, 2016 23:08
-
-
Save cfdrake/7148b86065798eeeeda3250ae2ab607f 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
//: Playground - noun: a place where people can play | |
/// A type which is buildable and appendable from a zero value. | |
protocol Monoid { | |
/// Returns the zero value. | |
static func empty() -> Self | |
/// Appends one Monoid value to another. | |
func append(_ m: Self) -> Self | |
} | |
extension Monoid { | |
/// Helper to concatenate together a list of Monoid values. | |
static func concatenate(_ ms: [Self]) -> Self { | |
guard let first = ms.first else { fatalError() } | |
let next = ms.dropFirst() | |
return next.reduce(first) { (acc, m) -> Self in | |
return acc.append(m) | |
} | |
} | |
} | |
/// Int's adherence to Monoid via addition. | |
/// Could also be implemented using multiplication. | |
/// We'll see an example of a type implemented two ways next. | |
extension Int: Monoid { | |
internal func append(_ m: Int) -> Int { | |
return self + m | |
} | |
static func empty() -> Int { | |
return 0 | |
} | |
} | |
// Examples... | |
Int.empty().append(3).append(4) | |
Int.concatenate([.empty(), 3, 4]) | |
/// Bool's adherence to Monoid (one way, via logical OR). | |
struct AnyOf: Monoid, ExpressibleByBooleanLiteral { | |
let bool: Bool | |
init(booleanLiteral value: Bool) { | |
bool = value | |
} | |
static func empty() -> AnyOf { | |
return false | |
} | |
func append(_ m: AnyOf) -> AnyOf { | |
return AnyOf(booleanLiteral: bool || m.bool) | |
} | |
} | |
/// Bool's adherence to Monoid (second way, via logical AND). | |
struct AllOf: Monoid, ExpressibleByBooleanLiteral { | |
let bool: Bool | |
init(booleanLiteral value: Bool) { | |
bool = value | |
} | |
static func empty() -> AllOf { | |
return true | |
} | |
func append(_ m: AllOf) -> AllOf { | |
return AllOf(booleanLiteral: bool || m.bool) | |
} | |
} | |
// Examples... | |
AnyOf.concatenate([false, true, false]).bool // true | |
AllOf.concatenate([false, false, false]).bool // false | |
AllOf.concatenate([true, true]).bool // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment