Skip to content

Instantly share code, notes, and snippets.

@cjnevin
Last active March 6, 2019 18:51
Show Gist options
  • Save cjnevin/9e9ef3f4f9a2f223c723ace9b0a959bf to your computer and use it in GitHub Desktop.
Save cjnevin/9e9ef3f4f9a2f223c723ace9b0a959bf to your computer and use it in GitHub Desktop.
import Foundation
infix operator <>: AdditionPrecedence
public protocol Semigroup {
func combine(with other: Self) -> Self
static func <> (lhs: Self, rhs: Self) -> Self
}
extension Semigroup {
public static func <> (lhs: Self, rhs: Self) -> Self {
return lhs.combine(with: rhs)
}
}
extension Numeric where Self: Semigroup {
public func combine(with other: Self) -> Self {
return self + other
}
}
extension Int: Semigroup { }
extension Array: Semigroup {
public func combine(with other: Array) -> Array {
return self + other
}
}
extension String: Semigroup {
public func combine(with other: String) -> String {
return self + other
}
}
extension Bool: Semigroup {
public func combine(with other: Bool) -> Bool {
return self && other
}
}
public func concat<S: Semigroup>(_ values: [S], initial: S) -> S {
return values.reduce(initial, <>)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment