org.scalactic.anyvals.NonEmptySet.scala Maven / Gradle / Ivy
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalactic.anyvals
import scala.annotation.unchecked.{ uncheckedVariance => uV }
import scala.collection.GenIterable
import scala.collection.GenSet
import scala.collection.GenTraversableOnce
import scala.collection.generic.CanBuildFrom
import scala.collection.mutable.Buffer
import scala.reflect.ClassTag
import scala.collection.immutable
import scala.collection.mutable.ArrayBuffer
import org.scalactic.Every
// Can't be a LinearSeq[T] because Builder would be able to create an empty one.
/**
* A non-empty Set: an ordered, immutable, non-empty collection of elements with LinearSeq
performance characteristics.
*
*
* The purpose of NonEmptySet
is to allow you to express in a type that a Set
is non-empty, thereby eliminating the
* need for (and potential exception from) a run-time check for non-emptiness. For a non-empty sequence with IndexedSeq
* performance, see Every
.
*
*
* Constructing NonEmptySet
s
*
*
* You can construct a NonEmptySet
by passing one or more elements to the NonEmptySet.apply
factory method:
*
*
*
* scala> NonEmptySet(1, 2, 3)
* res0: org.scalactic.anyvals.NonEmptySet[Int] = NonEmptySet(1, 2, 3)
*
*
*
* Alternatively you can cons elements onto the End
singleton object, similar to making a Set
starting with Nil
:
*
*
*
* scala> 1 :: 2 :: 3 :: Nil
* res0: Set[Int] = Set(1, 2, 3)
*
* scala> 1 :: 2 :: 3 :: End
* res1: org.scalactic.NonEmptySet[Int] = NonEmptySet(1, 2, 3)
*
*
*
* Note that although Nil
is a Set[Nothing]
, End
is
* not a NonEmptySet[Nothing]
, because no empty NonEmptySet
exists. (A non-empty Set is a series
* of connected links; if you have no links, you have no non-empty Set.)
*
*
*
* scala> val nil: Set[Nothing] = Nil
* nil: Set[Nothing] = Set()
*
* scala> val nada: NonEmptySet[Nothing] = End
* <console>:16: error: type mismatch;
* found : org.scalactic.anyvals.End.type
* required: org.scalactic.anyvals.NonEmptySet[Nothing]
* val nada: NonEmptySet[Nothing] = End
* ^
*
*
* Working with NonEmptySet
s
*
*
* NonEmptySet
does not extend Scala's Seq
or Traversable
traits because these require that
* implementations may be empty. For example, if you invoke tail
on a Seq
that contains just one element,
* you'll get an empty Seq
:
*
*
*
* scala> Set(1).tail
* res6: Set[Int] = Set()
*
*
*
* On the other hand, many useful methods exist on Seq
that when invoked on a non-empty Seq
are guaranteed
* to not result in an empty Seq
. For convenience, NonEmptySet
defines a method corresponding to every such Seq
* method. Here are some examples:
*
*
*
* NonEmptySet(1, 2, 3).map(_ + 1) // Result: NonEmptySet(2, 3, 4)
* NonEmptySet(1).map(_ + 1) // Result: NonEmptySet(2)
* NonEmptySet(1, 2, 3).containsSlice(NonEmptySet(2, 3)) // Result: true
* NonEmptySet(1, 2, 3).containsSlice(NonEmptySet(3, 4)) // Result: false
* NonEmptySet(-1, -2, 3, 4, 5).minBy(_.abs) // Result: -1
*
*
*
* NonEmptySet
does not currently define any methods corresponding to Seq
methods that could result in
* an empty Seq
. However, an implicit converison from NonEmptySet
to Set
* is defined in the NonEmptySet
companion object that will be applied if you attempt to call one of the missing methods. As a
* result, you can invoke filter
on an NonEmptySet
, even though filter
could result
* in an empty sequence—but the result type will be Set
instead of NonEmptySet
:
*
*
*
* NonEmptySet(1, 2, 3).filter(_ < 10) // Result: Set(1, 2, 3)
* NonEmptySet(1, 2, 3).filter(_ > 10) // Result: Set()
*
*
*
*
* You can use NonEmptySet
s in for
expressions. The result will be an NonEmptySet
unless
* you use a filter (an if
clause). Because filters are desugared to invocations of filter
, the
* result type will switch to a Set
at that point. Here are some examples:
*
*
*
* scala> import org.scalactic.anyvals._
* import org.scalactic.anyvals._
*
* scala> for (i <- NonEmptySet(1, 2, 3)) yield i + 1
* res0: org.scalactic.anyvals.NonEmptySet[Int] = NonEmptySet(2, 3, 4)
*
* scala> for (i <- NonEmptySet(1, 2, 3) if i < 10) yield i + 1
* res1: Set[Int] = Set(2, 3, 4)
*
* scala> for {
* | i <- NonEmptySet(1, 2, 3)
* | j <- NonEmptySet('a', 'b', 'c')
* | } yield (i, j)
* res3: org.scalactic.anyvals.NonEmptySet[(Int, Char)] =
* NonEmptySet((1,a), (1,b), (1,c), (2,a), (2,b), (2,c), (3,a), (3,b), (3,c))
*
* scala> for {
* | i <- NonEmptySet(1, 2, 3) if i < 10
* | j <- NonEmptySet('a', 'b', 'c')
* | } yield (i, j)
* res6: Set[(Int, Char)] =
* Set((1,a), (1,b), (1,c), (2,a), (2,b), (2,c), (3,a), (3,b), (3,c))
*
*
* @tparam T the type of elements contained in this NonEmptySet
*/
final class NonEmptySet[T] private (val toSet: Set[T]) extends AnyVal {
/**
* Returns a new NonEmptySet
containing the elements of this NonEmptySet
followed by the elements of the passed NonEmptySet
.
* The element type of the resulting NonEmptySet
is the most specific superclass encompassing the element types of this and the passed NonEmptySet
.
*
* @tparam U the element type of the returned NonEmptySet
* @param other the NonEmptySet
to append
* @return a new NonEmptySet
that contains all the elements of this NonEmptySet
followed by all elements of other
.
*/
def ++[U >: T](other: NonEmptySet[U]): NonEmptySet[U] = new NonEmptySet(toSet ++ other.toSet)
/**
* Returns a new NonEmptySet
containing the elements of this NonEmptySet
followed by the elements of the passed Every
.
* The element type of the resulting NonEmptySet
is the most specific superclass encompassing the element types of this NonEmptySet
and the passed Every
.
*
* @tparam U the element type of the returned NonEmptySet
* @param other the Every
to append
* @return a new NonEmptySet
that contains all the elements of this NonEmptySet
followed by all elements of other
.
*/
def ++[U >: T](other: Every[U]): NonEmptySet[U] = new NonEmptySet(toSet ++ other.toVector)
// TODO: Have I added these extra ++, etc. methods to Every that take a NonEmptySet?
/**
* Returns a new NonEmptySet
containing the elements of this NonEmptySet
followed by the elements of the passed GenTraversableOnce
.
* The element type of the resulting NonEmptySet
is the most specific superclass encompassing the element types of this NonEmptySet
* and the passed GenTraversableOnce
.
*
* @param other the GenTraversableOnce
to append
* @return a new NonEmptySet
that contains all the elements of this NonEmptySet
followed by all elements of other
.
*/
def ++(other: org.scalactic.ColCompatHelper.IterableOnce[T]): NonEmptySet[T] =
if (other.isEmpty) this else new NonEmptySet(toSet ++ other.toSet)
/**
* Returns a new NonEmptySet
with the given element added.
*
*
* @param element the element to add to this NonEmptySet
* @return a new NonEmptySet
consisting of element
and all elements of this NonEmptySet
.
*/
final def +(element: T): NonEmptySet[T] = new NonEmptySet(toSet + element)
/**
* Returns a new NonEmptySet
with the given element added.
*
* @param elem1 the first element to add.
* @param elem2 the second element to add.
* @param elems the remaining elements to add.
* @return a new NonEmptySet
with the given elements added, omitting duplicates.
*/
final def +(elem1: T, elem2: T, elems: T*): NonEmptySet[T] = new NonEmptySet(toSet + elem1 + elem2 ++ elems)
/**
* Appends all elements of this NonEmptySet
to a string builder. The written text will consist of a concatenation of the result of invoking toString
* on of every element of this NonEmptySet
, without any separator string.
*
* @param sb the string builder to which elements will be appended
* @return the string builder, sb
, to which elements were appended.
*/
final def addString(sb: StringBuilder): StringBuilder = toSet.addString(sb)
/**
* Check if an element exists at its index in the NonEmptySet
.
*
* @return true
if a element exists in NonEmptySet
at index idx
, where false
indicates the element at index idx
does not exist.
*/
final def apply(elem: T): Boolean = toSet(elem)
/**
* Appends all elements of this NonEmptySet
to a string builder using a separator string. The written text will consist of a concatenation of the
* result of invoking toString
* on of every element of this NonEmptySet
, separated by the string sep
.
*
* @param sb the string builder to which elements will be appended
* @param sep the separator string
* @return the string builder, sb
, to which elements were appended.
*/
final def addString(sb: StringBuilder, sep: String): StringBuilder = toSet.addString(sb, sep)
/**
* Appends all elements of this NonEmptySet
to a string builder using start, end, and separator strings. The written text will consist of a concatenation of
* the string start
; the result of invoking toString
on all elements of this NonEmptySet
,
* separated by the string sep
; and the string end
*
* @param sb the string builder to which elements will be appended
* @param start the starting string
* @param sep the separator string
* @param start the ending string
* @return the string builder, sb
, to which elements were appended.
*/
final def addString(sb: StringBuilder, start: String, sep: String, end: String): StringBuilder = toSet.addString(sb, start, sep, end)
/**
* Finds the first element of this NonEmptySet
for which the given partial function is defined, if any, and applies the partial function to it.
*
* @param pf the partial function
* @return an Option
containing pf
applied to the first element for which it is defined, or None
if
* the partial function was not defined for any element.
*/
final def collectFirst[U](pf: PartialFunction[T, U]): Option[U] = toSet.collectFirst(pf)
/**
* Indicates whether this NonEmptySet
contains a given value as an element.
*
* @param elem the element to look for
* @return true if this NonEmptySet
has an element that is equal (as determined by ==)
to elem
, false otherwise.
*/
final def contains(elem: T): Boolean = toSet.contains(elem)
/**
* Copies values of this NonEmptySet
to an array. Fills the given array arr
with values of this NonEmptySet
. Copying
* will stop once either the end of the current NonEmptySet
is reached, or the end of the array is reached.
*
* @param arr the array to fill
*/
final def copyToArray[U >: T](arr: Array[U]): Unit = toSet.copyToArray(arr)
/**
* Copies values of this NonEmptySet
to an array. Fills the given array arr
with values of this NonEmptySet
, beginning at
* index start
. Copying will stop once either the end of the current NonEmptySet
is reached, or the end of the array is reached.
*
* @param arr the array to fill
* @param start the starting index
*/
final def copyToArray[U >: T](arr: Array[U], start: Int): Unit = toSet.copyToArray(arr, start)
/**
* Copies values of this NonEmptySet
to an array. Fills the given array arr
with at most len
elements of this NonEmptySet
, beginning at
* index start
. Copying will stop once either the end of the current NonEmptySet
is reached, the end of the array is reached, or
* len
elements have been copied.
*
* @param arr the array to fill
* @param start the starting index
* @param len the maximum number of elements to copy
*/
final def copyToArray[U >: T](arr: Array[U], start: Int, len: Int): Unit = toSet.copyToArray(arr, start, len)
/**
* Copies all elements of this NonEmptySet
to a buffer.
*
* @param buf the buffer to which elements are copied
*/
final def copyToBuffer[U >: T](buf: Buffer[U]): Unit = toSet.copyToBuffer(buf)
/**
* Counts the number of elements in this NonEmptySet
that satisfy a predicate.
*
* @param p the predicate used to test elements.
* @return the number of elements satisfying the predicate p
.
*/
final def count(p: T => Boolean): Int = toSet.count(p)
/**
* Indicates whether a predicate holds for at least one of the elements of this NonEmptySet
.
*
* @param p the predicate used to test elements.
* @return true
if the given predicate p
holds for some of the elements of this NonEmptySet
, otherwise false
.
*/
final def exists(p: T => Boolean): Boolean = toSet.exists(p)
/**
* Finds the first element of this NonEmptySet
that satisfies the given predicate, if any.
*
* @param p the predicate used to test elements
* @return an Some
containing the first element in this NonEmptySet
that satisfies p
, or None
if none exists.
*/
final def find(p: T => Boolean): Option[T] = toSet.find(p)
/**
* Builds a new NonEmptySet
by applying a function to all elements of this NonEmptySet
and using the elements of the resulting NonEmptySet
s.
*
* @tparam U the element type of the returned NonEmptySet
* @param f the function to apply to each element.
* @return a new NonEmptySet
containing elements obtained by applying the given function f
to each element of this NonEmptySet
and concatenating
* the elements of resulting NonEmptySet
s.
*/
final def flatMap[U](f: T => NonEmptySet[U]): NonEmptySet[U] = {
val buf = new ArrayBuffer[U]
for (ele <- toSet)
buf ++= f(ele).toSet
new NonEmptySet(buf.toSet)
}
/**
* Converts this NonEmptySet
of NonEmptySet
s into a NonEmptySet
* formed by the elements of the nested NonEmptySet
s.
*
*
* Note: You cannot use this flatten
method on a NonEmptySet
that contains a GenTraversableOnce
s, because
* if all the nested GenTraversableOnce
s were empty, you'd end up with an empty NonEmptySet
.
*
*
* @tparm B the type of the elements of each nested NonEmptySet
* @return a new NonEmptySet
resulting from concatenating all nested NonEmptySet
s.
*/
final def flatten[B](implicit ev: T <:< NonEmptySet[B]): NonEmptySet[B] = flatMap(ev)
/**
* Folds the elements of this NonEmptySet
using the specified associative binary operator.
*
*
* The order in which operations are performed on elements is unspecified and may be nondeterministic.
*
*
* @tparam U a type parameter for the binary operator, a supertype of T.
* @param z a neutral element for the fold operation; may be added to the result an arbitrary number of
* times, and must not change the result (e.g., Nil
for Set concatenation,
* 0 for addition, or 1 for multiplication.)
* @param op a binary operator that must be associative
* @return the result of applying fold operator op
between all the elements and z
*/
final def fold[U >: T](z: U)(op: (U, U) => U): U = toSet.fold(z)(op)
/**
* Applies a binary operator to a start value and all elements of this NonEmptySet
, going left to right.
*
* @tparam B the result type of the binary operator.
* @param z the start value.
* @param op the binary operator.
* @return the result of inserting op
between consecutive elements of this NonEmptySet
, going left to right, with the start value,
* z
, on the left:
*
*
* op(...op(op(z, x_1), x_2), ..., x_n)
*
*
*
* where x1, ..., xn are the elements of this NonEmptySet
.
*
*/
final def foldLeft[B](z: B)(op: (B, T) => B): B = toSet.foldLeft(z)(op)
/**
* Applies a binary operator to all elements of this NonEmptySet
and a start value, going right to left.
*
* @tparam B the result of the binary operator
* @param z the start value
* @param op the binary operator
* @return the result of inserting op
between consecutive elements of this NonEmptySet
, going right to left, with the start value,
* z
, on the right:
*
*
* op(x_1, op(x_2, ... op(x_n, z)...))
*
*
*
* where x1, ..., xn are the elements of this NonEmptySet
.
*
*/
final def foldRight[B](z: B)(op: (T, B) => B): B = toSet.foldRight(z)(op)
/**
* Indicates whether a predicate holds for all elements of this NonEmptySet
.
*
* @param p the predicate used to test elements.
* @return true
if the given predicate p
holds for all elements of this NonEmptySet
, otherwise false
.
*/
final def forall(p: T => Boolean): Boolean = toSet.forall(p)
/**
* Applies a function f
to all elements of this NonEmptySet
.
*
* @param f the function that is applied for its side-effect to every element. The result of function f
is discarded.
*/
final def foreach(f: T => Unit): Unit = toSet.foreach(f)
/**
* Partitions this NonEmptySet
into a map of NonEmptySet
s according to some discriminator function.
*
* @tparam K the type of keys returned by the discriminator function.
* @param f the discriminator function.
* @return A map from keys to NonEmptySet
s such that the following invariant holds:
*
*
* (NonEmptySet.toSet partition f)(k) = xs filter (x => f(x) == k)
*
*
*
* That is, every key k
is bound to a NonEmptySet
of those elements x
for which f(x)
equals k
.
*
*/
final def groupBy[K](f: T => K): Map[K, NonEmptySet[T]] = {
val mapKToSet = toSet.groupBy(f)
mapKToSet.mapValues { Set => new NonEmptySet(Set) }.toMap
}
/**
* Partitions elements into fixed size NonEmptySet
s.
*
* @param size the number of elements per group
* @return An iterator producing NonEmptySet
s of size size
, except the last will be truncated if the elements don't divide evenly.
*/
final def grouped(size: Int): Iterator[NonEmptySet[T]] = {
val itOfSet = toSet.grouped(size)
itOfSet.map { Set => new NonEmptySet(Set) }
}
/**
* Returns true
to indicate this NonEmptySet
has a definite size, since all NonEmptySet
s are strict collections.
*/
final def hasDefiniteSize: Boolean = true
// override def hashCode: Int = toSet.hashCode
/**
* Selects the first element of this NonEmptySet
.
*
* @return the first element of this NonEmptySet
.
*/
final def head: T = toSet.head
// Methods like headOption I can't get rid of because of the implicit conversion to GenTraversable.
// Users can call any of the methods I've left out on a NonEmptySet, and get whatever Set would return
// for that method call. Eventually I'll probably implement them all to save the implicit conversion.
/**
* Selects the first element of this NonEmptySet
and returns it wrapped in a Some
.
*
* @return the first element of this NonEmptySet
, wrapped in a Some
.
*/
final def headOption: Option[T] = toSet.headOption
/**
* Returns false
to indicate this NonEmptySet
, like all NonEmptySet
s, is non-empty.
*
* @return false
*/
final def isEmpty: Boolean = false
/**
* Returns true
to indicate this NonEmptySet
, like all NonEmptySet
s, can be traversed repeatedly.
*
* @return true
*/
final def isTraversableAgain: Boolean = true
/**
* Creates and returns a new iterator over all elements contained in this NonEmptySet
.
*
* @return the new iterator
*/
final def iterator: Iterator[T] = toSet.iterator
/**
* Selects the last element of this NonEmptySet
.
*
* @return the last element of this NonEmptySet
.
*/
final def last: T = toSet.last
/**
* Returns the last element of this NonEmptySet
, wrapped in a Some
.
*
* @return the last element, wrapped in a Some
.
*/
final def lastOption: Option[T] = toSet.lastOption // Will always return a Some
/**
* Builds a new NonEmptySet
by applying a function to all elements of this NonEmptySet
.
*
* @tparam U the element type of the returned NonEmptySet
.
* @param f the function to apply to each element.
* @return a new NonEmptySet
resulting from applying the given function f
to each element of this NonEmptySet
and collecting the results.
*/
final def map[U](f: T => U): NonEmptySet[U] =
new NonEmptySet(toSet.map(f))
/**
* Finds the largest element.
*
* @return the largest element of this NonEmptySet
.
*/
final def max[U >: T](implicit cmp: Ordering[U]): T = toSet.max(cmp)
/**
* Finds the largest result after applying the given function to every element.
*
* @return the largest result of applying the given function to every element of this NonEmptySet
.
*/
final def maxBy[U](f: T => U)(implicit cmp: Ordering[U]): T = toSet.maxBy(f)(cmp)
/**
* Finds the smallest element.
*
* @return the smallest element of this NonEmptySet
.
*/
final def min[U >: T](implicit cmp: Ordering[U]): T = toSet.min(cmp)
/**
* Finds the smallest result after applying the given function to every element.
*
* @return the smallest result of applying the given function to every element of this NonEmptySet
.
*/
final def minBy[U](f: T => U)(implicit cmp: Ordering[U]): T = toSet.minBy(f)(cmp)
/**
* Displays all elements of this NonEmptySet
in a string.
*
* @return a string representation of this NonEmptySet
. In the resulting string, the result of invoking toString
on all elements of this
* NonEmptySet
follow each other without any separator string.
*/
final def mkString: String = toSet.mkString
/**
* Displays all elements of this NonEmptySet
in a string using a separator string.
*
* @param sep the separator string
* @return a string representation of this NonEmptySet
. In the resulting string, the result of invoking toString
on all elements of this
* NonEmptySet
are separated by the string sep
.
*/
final def mkString(sep: String): String = toSet.mkString(sep)
/**
* Displays all elements of this NonEmptySet
in a string using start, end, and separator strings.
*
* @param start the starting string.
* @param sep the separator string.
* @param end the ending string.
* @return a string representation of this NonEmptySet
. The resulting string begins with the string start
and ends with the string
* end
. Inside, In the resulting string, the result of invoking toString
on all elements of this NonEmptySet
are
* separated by the string sep
.
*/
final def mkString(start: String, sep: String, end: String): String = toSet.mkString(start, sep, end)
/**
* Returns true
to indicate this NonEmptySet
, like all NonEmptySet
s, is non-empty.
*
* @return true
*/
final def nonEmpty: Boolean = true
/**
* The result of multiplying all the elements of this NonEmptySet
.
*
*
* This method can be invoked for any NonEmptySet[T]
for which an implicit Numeric[T]
exists.
*
*
* @return the product of all elements
*/
final def product[U >: T](implicit num: Numeric[U]): U = toSet.product(num)
/**
* Reduces the elements of this NonEmptySet
using the specified associative binary operator.
*
*
* The order in which operations are performed on elements is unspecified and may be nondeterministic.
*
*
* @tparam U a type parameter for the binary operator, a supertype of T.
* @param op a binary operator that must be associative.
* @return the result of applying reduce operator op
between all the elements of this NonEmptySet
.
*/
final def reduce[U >: T](op: (U, U) => U): U = toSet.reduce(op)
/**
* Applies a binary operator to all elements of this NonEmptySet
, going left to right.
*
* @tparam U the result type of the binary operator.
* @param op the binary operator.
* @return the result of inserting op
between consecutive elements of this NonEmptySet
, going left to right:
*
*
* op(...op(op(x_1, x_2), x_3), ..., x_n)
*
*
*
* where x1, ..., xn are the elements of this NonEmptySet
.
*
*/
final def reduceLeft[U >: T](op: (U, T) => U): U = toSet.reduceLeft(op)
/**
* Applies a binary operator to all elements of this NonEmptySet
, going left to right, returning the result in a Some
.
*
* @tparam U the result type of the binary operator.
* @param op the binary operator.
* @return a Some
containing the result of reduceLeft(op)
*
*/
final def reduceLeftOption[U >: T](op: (U, T) => U): Option[U] = toSet.reduceLeftOption(op)
final def reduceOption[U >: T](op: (U, U) => U): Option[U] = toSet.reduceOption(op)
/**
* Applies a binary operator to all elements of this NonEmptySet
, going right to left.
*
* @tparam U the result of the binary operator
* @param op the binary operator
* @return the result of inserting op
between consecutive elements of this NonEmptySet
, going right to left:
*
*
* op(x_1, op(x_2, ... op(x_{n-1}, x_n)...))
*
*
*
* where x1, ..., xn are the elements of this NonEmptySet
.
*
*/
final def reduceRight[U >: T](op: (T, U) => U): U = toSet.reduceRight(op)
/**
* Applies a binary operator to all elements of this NonEmptySet
, going right to left, returning the result in a Some
.
*
* @tparam U the result of the binary operator
* @param op the binary operator
* @return a Some
containing the result of reduceRight(op)
*/
final def reduceRightOption[U >: T](op: (T, U) => U): Option[U] = toSet.reduceRightOption(op)
/**
* Checks if the given GenIterable
contains the same elements in the same order as this NonEmptySet
.
*
* @param that the GenIterable
with which to compare
* @return true
, if both this NonEmptySet
and the given GenIterable
contain the same elements
* in the same order, false
otherwise.
*/
final def sameElements[U >: T](that: GenIterable[U]): Boolean = toSet.sameElements(that)
/**
* Checks if the given Every
contains the same elements in the same order as this NonEmptySet
.
*
* @param that the Every
with which to compare
* @return true
, if both this and the given Every
contain the same elements
* in the same order, false
otherwise.
*/
final def sameElements[U >: T](that: Every[U]): Boolean = toSet.sameElements(that.toVector)
/**
* Checks if the given NonEmptySet
contains the same elements in the same order as this NonEmptySet
.
*
* @param that the NonEmptySet
with which to compare
* @return true
, if both this and the given NonEmptySet
contain the same elements
* in the same order, false
otherwise.
*/
final def sameElements[U >: T](that: NonEmptySet[U]): Boolean = toSet.sameElements(that.toSet)
/**
* Computes a prefix scan of the elements of this NonEmptySet
.
*
*
* Note: The neutral element z may be applied more than once.
*
*
*
* Here are some examples:
*
*
*
* NonEmptySet(1, 2, 3).scan(0)(_ + _) == NonEmptySet(0, 1, 3, 6)
* NonEmptySet(1, 2, 3).scan("z")(_ + _.toString) == NonEmptySet("z", "z1", "z12", "z123")
*
*
* @tparam U a type parameter for the binary operator, a supertype of T, and the type of the resulting NonEmptySet
.
* @param z a neutral element for the scan operation; may be added to the result an arbitrary number of
* times, and must not change the result (e.g., Nil
for Set concatenation,
* 0 for addition, or 1 for multiplication.)
* @param op a binary operator that must be associative
* @return a new NonEmptySet
containing the prefix scan of the elements in this NonEmptySet
*/
final def scan[U >: T](z: U)(op: (U, U) => U): NonEmptySet[U] = new NonEmptySet(toSet.scan(z)(op))
/**
* Produces a NonEmptySet
containing cumulative results of applying the operator going left to right.
*
*
* Here are some examples:
*
*
*
* NonEmptySet(1, 2, 3).scanLeft(0)(_ + _) == NonEmptySet(0, 1, 3, 6)
* NonEmptySet(1, 2, 3).scanLeft("z")(_ + _) == NonEmptySet("z", "z1", "z12", "z123")
*
*
* @tparam B the result type of the binary operator and type of the resulting NonEmptySet
* @param z the start value.
* @param op the binary operator.
* @return a new NonEmptySet
containing the intermediate results of inserting op
between consecutive elements of this NonEmptySet
,
* going left to right, with the start value, z
, on the left.
*/
final def scanLeft[B](z: B)(op: (B, T) => B): NonEmptySet[B] = new NonEmptySet(toSet.scanLeft(z)(op))
/**
* Produces a NonEmptySet
containing cumulative results of applying the operator going right to left.
*
*
* Here are some examples:
*
*
*
* NonEmptySet(1, 2, 3).scanRight(0)(_ + _) == NonEmptySet(6, 5, 3, 0)
* NonEmptySet(1, 2, 3).scanRight("z")(_ + _) == NonEmptySet("123z", "23z", "3z", "z")
*
*
* @tparam B the result of the binary operator and type of the resulting NonEmptySet
* @param z the start value
* @param op the binary operator
* @return a new NonEmptySet
containing the intermediate results of inserting op
between consecutive elements of this NonEmptySet
,
* going right to left, with the start value, z
, on the right.
*/
final def scanRight[B](z: B)(op: (T, B) => B): NonEmptySet[B] = new NonEmptySet(toSet.scanRight(z)(op))
/**
* Groups elements in fixed size blocks by passing a “sliding window” over them (as opposed to partitioning them, as is done in grouped.)
*
* @param size the number of elements per group
* @return an iterator producing NonEmptySet
s of size size
, except the last and the only element will be truncated
* if there are fewer elements than size
.
*/
final def sliding(size: Int): Iterator[NonEmptySet[T]] = toSet.sliding(size).map(new NonEmptySet(_))
/**
* Groups elements in fixed size blocks by passing a “sliding window” over them (as opposed to partitioning them, as is done in grouped.),
* moving the sliding window by a given step
each time.
*
* @param size the number of elements per group
* @param step the distance between the first elements of successive groups
* @return an iterator producing NonEmptySet
s of size size
, except the last and the only element will be truncated
* if there are fewer elements than size
.
*/
final def sliding(size: Int, step: Int): Iterator[NonEmptySet[T]] = toSet.sliding(size, step).map(new NonEmptySet(_))
/**
* The size of this NonEmptySet
.
*
*
* Note: length
and size
yield the same result, which will be >
= 1.
*
*
* @return the number of elements in this NonEmptySet
.
*/
final def size: Int = toSet.size
/**
* Returns "NonEmptySet"
, the prefix of this object's toString
representation.
*
* @return the string "NonEmptySet"
*/
def stringPrefix: String = "NonEmptySet"
/**
* The result of summing all the elements of this NonEmptySet
.
*
*
* This method can be invoked for any NonEmptySet[T]
for which an implicit Numeric[T]
exists.
*
*
* @return the sum of all elements
*/
final def sum[U >: T](implicit num: Numeric[U]): U = toSet.sum(num)
import scala.language.higherKinds
/**
* Converts this NonEmptySet
into a collection of type Col
by copying all elements.
*
* @tparam Col the collection type to build.
* @return a new collection containing all elements of this NonEmptySet
.
*/
final def to[Col[_]](factory: org.scalactic.ColCompatHelper.Factory[T, Col[T @ uV]]): Col[T @ uV] =
toSet.to(factory)
/**
* Converts this NonEmptySet
to an array.
*
* @return an array containing all elements of this NonEmptySet
. A ClassTag
must be available for the element type of this NonEmptySet
.
*/
final def toArray[U >: T](implicit classTag: ClassTag[U]): Array[U] = toSet.toArray
/**
* Converts this NonEmptySet
to a Vector
.
*
* @return a Vector
containing all elements of this NonEmptySet
.
*/
final def toVector: Vector[T] = toSet.toVector
/**
* Converts this NonEmptySet
to a mutable buffer.
*
* @return a buffer containing all elements of this NonEmptySet
.
*/
final def toBuffer[U >: T]: Buffer[U] = toSet.toBuffer
/**
* Converts this NonEmptySet
to an immutable IndexedSeq
.
*
* @return an immutable IndexedSeq
containing all elements of this NonEmptySet
.
*/
final def toIndexedSeq: collection.immutable.IndexedSeq[T] = toSet.toVector
/**
* Converts this NonEmptySet
to an iterable collection.
*
* @return an Iterable
containing all elements of this NonEmptySet
.
*/
final def toIterable: Iterable[T] = toSet.toIterable
/**
* Returns an Iterator
over the elements in this NonEmptySet
.
*
* @return an Iterator
containing all elements of this NonEmptySet
.
*/
final def toIterator: Iterator[T] = toSet.toIterator
/**
* Converts this NonEmptySet
to a Set.
*
* @return a Set containing all elements of this NonEmptySet
.
*/
// final def toSet: Set[T] = toSet
/**
* Converts this NonEmptySet
to a map.
*
*
* This method is unavailable unless the elements are members of Tuple2
, each ((K, V))
becoming a key-value pair
* in the map. Duplicate keys will be overwritten by later keys.
*
*
* @return a map of type immutable.Map[K, V]
containing all key/value pairs of type (K, V)
of this NonEmptySet
.
*/
final def toMap[K, V](implicit ev: T <:< (K, V)): Map[K, V] = toSet.toMap
/**
* Converts this NonEmptySet
to an immutable IndexedSeq
.
*
* @return an immutable IndexedSeq
containing all elements of this NonEmptySet
.
*/
final def toSeq: Seq[T] = toSet.toSeq
/**
* Converts this NonEmptySet
to a set.
*
* @return a set containing all elements of this NonEmptySet
.
*/
final def toList: collection.immutable.List[T] = toSet.toList
/**
* Converts this NonEmptySet
to a stream.
*
* @return a stream containing all elements of this NonEmptySet
.
*/
final def toStream: Stream[T] = toSet.toStream
/**
* Returns a string representation of this NonEmptySet
.
*
* @return the string "NonEmptySet"
followed by the result of invoking toString
on
* this NonEmptySet
's elements, surrounded by parentheses.
*/
override def toString: String = "NonEmptySet(" + toSet.mkString(", ") + ")"
final def transpose[U](implicit ev: T <:< NonEmptySet[U]): NonEmptySet[NonEmptySet[U]] = {
val asSets = toSet.map(ev)
val Set = asSets.transpose
new NonEmptySet(Set.map(new NonEmptySet(_)))
}
/**
* Produces a new NonEmptySet
that contains all elements of this NonEmptySet
and also all elements of a given Every
.
*
*
* NonEmptySetX
union
everyY
is equivalent to NonEmptySetX
++
everyY
.
*
*
*
* Another way to express this is that NonEmptySetX
union
everyY
computes the order-presevring multi-set union
* of NonEmptySetX
and everyY
. This union
method is hence a counter-part of diff
and intersect
that
* also work on multi-sets.
*
*
* @param that the Every
to add.
* @return a new NonEmptySet
that contains all elements of this NonEmptySet
followed by all elements of that
Every
.
*/
final def union(that: Every[T]): NonEmptySet[T] = new NonEmptySet(toSet union that.toSet)
/**
* Produces a new NonEmptySet
that contains all elements of this NonEmptySet
and also all elements of a given NonEmptySet
.
*
*
* NonEmptySetX
union
NonEmptySetY
is equivalent to NonEmptySetX
++
NonEmptySetY
.
*
*
*
* Another way to express this is that NonEmptySetX
union
NonEmptySetY
computes the order-presevring multi-set union
* of NonEmptySetX
and NonEmptySetY
. This union
method is hence a counter-part of diff
and intersect
that
* also work on multi-sets.
*
*
* @param that the NonEmptySet
to add.
* @return a new NonEmptySet
that contains all elements of this NonEmptySet
followed by all elements of that
.
*/
final def union(that: NonEmptySet[T]): NonEmptySet[T] = new NonEmptySet(toSet union that.toSet)
/**
* Produces a new NonEmptySet
that contains all elements of this NonEmptySet
and also all elements of a given GenSeq
.
*
*
* NonEmptySetX
union
ys
is equivalent to NonEmptySetX
++
ys
.
*
*
*
* Another way to express this is that NonEmptySetX
union
ys
computes the order-presevring multi-set union
* of NonEmptySetX
and ys
. This union
method is hence a counter-part of diff
and intersect
that
* also work on multi-sets.
*
*
* @param that the GenSet
to add.
* @return a new NonEmptySet
that contains all elements of this NonEmptySet
followed by all elements of that
GenSeq
.
*/
final def union(that: GenSet[T]): NonEmptySet[T] = new NonEmptySet(toSet.union(that))
/**
* Converts this NonEmptySet
of pairs into two NonEmptySet
s of the first and second half of each pair.
*
* @tparam L the type of the first half of the element pairs
* @tparam R the type of the second half of the element pairs
* @param asPair an implicit conversion that asserts that the element type of this NonEmptySet
is a pair.
* @return a pair of NonEmptySet
s, containing the first and second half, respectively, of each element pair of this NonEmptySet
.
*/
final def unzip[L, R](implicit asPair: T => (L, R)): (NonEmptySet[L], NonEmptySet[R]) = {
val unzipped = toSet.unzip
(new NonEmptySet(unzipped._1), new NonEmptySet(unzipped._2))
}
/**
* Converts this NonEmptySet
of triples into three NonEmptySet
s of the first, second, and and third element of each triple.
*
* @tparam L the type of the first member of the element triples
* @tparam M the type of the second member of the element triples
* @tparam R the type of the third member of the element triples
* @param asTriple an implicit conversion that asserts that the element type of this NonEmptySet
is a triple.
* @return a triple of NonEmptySet
s, containing the first, second, and third member, respectively, of each element triple of this NonEmptySet
.
*/
final def unzip3[L, M, R](implicit asTriple: T => (L, M, R)): (NonEmptySet[L], NonEmptySet[M], NonEmptySet[R]) = {
val unzipped = toSet.unzip3
(new NonEmptySet(unzipped._1), new NonEmptySet(unzipped._2), new NonEmptySet(unzipped._3))
}
/**
* Returns a NonEmptySet
formed from this NonEmptySet
and an iterable collection by combining corresponding
* elements in pairs. If one of the two collections is shorter than the other, placeholder elements will be used to extend the
* shorter collection to the length of the longer.
*
* @tparm O the type of the second half of the returned pairs
* @tparm U the type of the first half of the returned pairs
* @param other the Iterable
providing the second half of each result pair
* @param thisElem the element to be used to fill up the result if this NonEmptySet
is shorter than that
Iterable
.
* @param otherElem the element to be used to fill up the result if that
Iterable
is shorter than this NonEmptySet
.
* @return a new NonEmptySet
containing pairs consisting of corresponding elements of this NonEmptySet
and that
. The
* length of the returned collection is the maximum of the lengths of this NonEmptySet
and that
. If this NonEmptySet
* is shorter than that
, thisElem
values are used to pad the result. If that
is shorter than this
* NonEmptySet
, thatElem
values are used to pad the result.
*/
final def zipAll[O, U >: T](other: collection.Iterable[O], thisElem: U, otherElem: O): NonEmptySet[(U, O)] =
new NonEmptySet(toSet.zipAll(other, thisElem, otherElem))
/**
* Zips this NonEmptySet
with its indices.
*
* @return A new NonEmptySet
containing pairs consisting of all elements of this NonEmptySet
paired with their index. Indices start at 0.
*/
final def zipWithIndex: NonEmptySet[(T, Int)] = new NonEmptySet(toSet.zipWithIndex)
}
/**
* Companion object for class NonEmptySet
.
*/
object NonEmptySet {
/**
* Constructs a new NonEmptySet
given at least one element.
*
* @tparam T the type of the element contained in the new NonEmptySet
* @param firstElement the first element (with index 0) contained in this NonEmptySet
* @param otherElements a varargs of zero or more other elements (with index 1, 2, 3, ...) contained in this NonEmptySet
*/
def apply[T](firstElement: T, otherElements: T*): NonEmptySet[T] = new NonEmptySet(otherElements.toSet + firstElement)
/**
* Variable argument extractor for NonEmptySet
s.
*
* @param nonEmptySet: the NonEmptySet
containing the elements to extract
* @return an Seq
containing this NonEmptySet
s elements, wrapped in a Some
*/
def unapplySeq[T](nonEmptySet: NonEmptySet[T]): Option[Seq[T]] = Some(nonEmptySet.toSeq)
/*
// TODO: Figure out how to get case NonEmptySet() to not compile
def unapplySeq[T](NonEmptySet: NonEmptySet[T]): Option[(T, Seq[T])] = Some(NonEmptySet.head, NonEmptySet.tail)
*/
/**
* Optionally construct a NonEmptySet
containing the elements, if any, of a given GenSet
.
*
* @param set the GenSet
with which to construct a NonEmptySet
* @return a NonEmptySet
containing the elements of the given GenSeq
, if non-empty, wrapped in
* a Some
; else None
if the GenSeq
is empty
*/
def from[T](set: GenSet[T]): Option[NonEmptySet[T]] =
set.headOption match {
case None => None
case Some(first) => Some(new NonEmptySet(scala.collection.immutable.Set.empty[T] ++ set))
}
import scala.language.implicitConversions
/**
* Implicit conversion from NonEmptySet
to Set
.
*
*
* One use case for this implicit conversion is to enable GenSeq[NonEmptySet]
s to be flattened.
* Here's an example:
*
*
*
* scala> Vector(NonEmptySet(1, 2, 3), NonEmptySet(3, 4), NonEmptySet(5, 6, 7, 8)).flatten
* res0: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 3, 4, 5, 6, 7, 8)
*
*
* @param NonEmptySet the NonEmptySet
to convert to a Set
* @return a Set
containing the elements, in order, of this NonEmptySet
*/
implicit def NonEmptySetToSet[E](NonEmptySet: NonEmptySet[E]): scala.collection.immutable.Set[E] = NonEmptySet.toSet
}