Skip to content

Instantly share code, notes, and snippets.

@erica
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save erica/9e573199411651d2825f to your computer and use it in GitHub Desktop.

Select an option

Save erica/9e573199411651d2825f to your computer and use it in GitHub Desktop.
Bag
//
// Bag.swift
// CmdLineTest
//
// Created by Erica Sadun on 6/23/14.
// Copyright (c) 2014 Erica Sadun. All rights reserved.
//
import Foundation
class Bag<T: Hashable> {
var _storage = Dictionary<T, Int>()
// MARK: Init
init(_ items : T ...)
{
self.addItems(items)
}
init(items : Array<T>)
{
self.addItems(items)
}
// MARK: Add
func addItem(item : T)
{
if let count = _storage[item] {
_storage[item] = count + 1
} else {
_storage[item] = 1
}
}
func addItems(items : Array<T>)
{
for item in items
{
self.addItem(item)
}
}
func addItems(items : T...)
{
self.addItems(items)
}
// MARK: Remove
func removeItem(item: T) {
if let count = _storage[item]
{
if (count > 1) {
_storage[item] = count - 1
} else {
_storage.removeValueForKey(item)
}
}
}
func removeItems(items : Array<T>)
{
for item in items
{
self.removeItem(item)
}
}
func removeItems(items : T...)
{
self.removeItems(items)
}
// MARK: Utility
func countForItem(item: T) -> Int? {
return _storage[item]
}
func members() -> T[] {
return Array(_storage.keys)
}
}
extension Bag : Printable {
var description : String {
return _storage.description
}
}
struct BagGenerator<T:Hashable> : Generator{
var _backingGenerator : DictionaryGenerator<T, Int>
init(_ backingDictionary : Dictionary<T, Int>) {
_backingGenerator = backingDictionary.generate()
}
typealias Element = (T, Int)
mutating func next() -> (T, Int)? {
return _backingGenerator.next()
}
}
extension Bag : Sequence {
typealias GeneratorType = BagGenerator<T>
func generate() -> BagGenerator<T>{
return BagGenerator<T>(_storage)
}
}
@erica

erica commented Jun 23, 2014

Copy link
Copy Markdown
Author

This has the advantage of extensibility to a 3-tuple, which is why the bag generator is structured as it is

@algal

algal commented Jun 23, 2014

Copy link
Copy Markdown

Do you mean by this that you could modify the BagGenerator so that BagGenerator.Element = (T, Int, SomethingElse) ?

@erica

erica commented Jun 23, 2014

Copy link
Copy Markdown
Author

Yes -- although in v2, I changed it back because I finished writing up that kind of extension. This is now more about the bag and less about the tuple

@erica

erica commented Jun 23, 2014

Copy link
Copy Markdown
Author

And voila, v2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment