All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.pure4j.collections.PersistentHashSet Maven / Gradle / Ivy

There is a newer version: 0.3.1
Show newest version
/**
 *   Copyright (c) Rich Hickey. All rights reserved.
 *   The use and distribution terms for this software are covered by the
 *   Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
 *   which can be found in the file epl-v10.html at the root of this distribution.
 *   By using this software in any fashion, you are agreeing to be bound by
 * 	 the terms of this license.
 *   You must not remove this notice, or any other, from this software.
 **/

/* rich Mar 3, 2008 */

package org.pure4j.collections;

import java.util.Collection;

import org.pure4j.Pure4J;
import org.pure4j.annotations.pure.Enforcement;
import org.pure4j.annotations.pure.Pure;
import org.pure4j.annotations.pure.PureParameters;

public class PersistentHashSet extends APersistentSet {

	static private final PersistentHashSet EMPTY = new PersistentHashSet(
			PersistentHashMap.emptyMap());

	@SuppressWarnings("unchecked")
	public static  PersistentHashSet emptySet() {
		return (PersistentHashSet) EMPTY;
	}

	@SuppressWarnings("unchecked")
	public static  PersistentHashSet create(K... init) {
		ITransientMap map = (ITransientMap) PersistentHashMap.emptyMap().asTransient();
		for (int i = 0; i < init.length; i++) {
			map.put(init[i], init[i]);
		}
		return new PersistentHashSet(map.persistent());
	}

	public PersistentHashSet(Collection init) {
		this(createMap(init));
	}

	

	public PersistentHashSet(ISeq items) {
		this(createMap(items));
	}

	@Pure
	@PureParameters(Enforcement.NOT_PURE)
	private static  IPersistentMap createMap(ISeq items) {
		ITransientMap map = new TransientHashMap();
		for (; items != null; items = items.next()) {
			K first = items.first();
			map.put(first, first);
		}
		return map.persistent();
	}
	
	@Pure
	@PureParameters(Enforcement.NOT_PURE)
	private static  IPersistentMap createMap(Collection init) {
		ITransientMap map = new TransientHashMap();
		for (K key : init) {
			map.put(key, key);
		}
		return map.persistent();
	}

	private PersistentHashSet(IPersistentMap impl) {
		super(impl);
	}

	public IPersistentSet disjoin(Object key) {
		Pure4J.immutable(key);
		if (contains(key))
			return new PersistentHashSet(impl.without(key));
		return this;
	}

	public IPersistentSet cons(K o) {
		Pure4J.immutable(o);
		if (contains(o))
			return this;
		return new PersistentHashSet(impl.assoc(o, o));
	}

	@SuppressWarnings("unchecked")
	public PersistentHashSet empty() {
		return (PersistentHashSet) EMPTY;
	}

	public ITransientSet asTransient() {
		return new TransientHashSet(this);
	}

}