Advertisement
Revolucent

Swift Monoid

Aug 8th, 2018
555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.24 KB | None | 0 0
  1. infix operator <>: AdditionPrecedence
  2.  
  3. public protocol Monoid {
  4.     static var empty: Self { get }
  5.     static func <>(lhs: Self, rhs: Self) -> Self
  6. }
  7.  
  8. public extension Sequence where Element: Monoid {
  9.     func concat() -> Element {
  10.         return reduce(Element.empty, <>)
  11.     }
  12. }
  13.  
  14. extension Array: Monoid {
  15.     public static var empty: [Element] { return [] }
  16.     public static func <>(lhs: [Element], rhs: [Element]) -> [Element] {
  17.         return lhs.appending(rhs)      
  18.     }
  19. }
  20.  
  21. extension Dictionary: Monoid {
  22.     public static var empty: [Key: Value] { return [:] }
  23.     public static func <>(lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
  24.         return lhs.merging(rhs, uniquingKeysWith: { _, newKey in newKey })
  25.     }
  26. }
  27.  
  28. extension Set: Monoid {
  29.     public static var empty: Set<Element> { return [] }
  30.     public static func <>(lhs: Set<Element>, rhs: Set<Element>) -> Set<Element> {
  31.         return lhs.union(rhs)
  32.     }
  33. }
  34.  
  35. extension Optional: Monoid where Wrapped: Monoid {
  36.     public static var empty: Wrapped? { return nil }
  37.     public static func <>(lhs: Wrapped?, rhs: Wrapped?) -> Wrapped? {
  38.         guard let lhs = lhs else { return rhs }
  39.         guard let rhs = rhs else { return lhs }
  40.         return lhs <> rhs
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement