Last active
March 6, 2019 18:51
-
-
Save cjnevin/9e9ef3f4f9a2f223c723ace9b0a959bf 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 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