/** * Beispiel aus * * - Algorithmen und Datenstrukturen für Dummies * - von Andreas Gogol-Döring und Thomas Letschert * - Verlag Wiley-VCH; Oktober 2019 * - Kapitel 9, Mengen und ihre Speicherung * * @author A. Gogol-Döring, Th. Letschert */ import Foundation protocol SetElement : CustomStringConvertible, Equatable {} protocol Set { associatedtype ElemType: SetElement associatedtype OtherSetType: Set where OtherSetType.ElemType == ElemType associatedtype RepType init(_ elements: [ElemType]) func intersection(other: OtherSetType) -> OtherSetType func contains(x: ElemType) -> Bool } extension Int: SetElement {} struct AuD_09_02_SetFuncListBased { struct ListSet: Set, CustomStringConvertible { typealias ElemType = A typealias OtherSetType = ListSet typealias RepType = [A] private let elements: [A] /*init(_ elements: A...) { self.elements = elements }*/ init(_ elements: [A]) { self.elements = elements } func intersection(other: OtherSetType) -> OtherSetType { return ListSet( self.elements.filter( { x in other.elements.contains(where: { y in x == y} ) } ) ) } func contains(x: ElemType) -> Bool { elements.contains(x) } var description: String { "{\(elements.map( { (x: A) in x.description } ).joined(separator: ","))}" } } static func run() { let set1 = ListSet([1, 2, 3, 4, 5]) let set2 = ListSet([2, 4, 6, 8]) print(set1.intersection(other: set2)) } }