- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Re: New Collections: can we decrease the noise level?
Sun, 2009-11-15, 05:11
David, with minor changes, that really works. So, if I add the following to the library:
trait From[-Fr,-Elem] { type CanBuild[+To[Elem]] = CanBuildFrom[Fr,Elem,To[Elem]]}
type TraversableType[A, CC[T] <: Traversable[T] withTraversableLike[T,CC[T]] with GenericTraversableTemplate[T, CC]] = Traversable[A] with TraversableLike[A,CC[A]] with GenericTraversableTemplate[A, CC]
Then the two examples can be thus simplified:
def quicksort [T <% Ordered[T], CC[X] <: TraversableType[X,CC] : From[CC[T],T]#CanBuild] (coll: CC[T]): CC[T] = if (coll.isEmpty) { coll } else { val (smaller, bigger) = coll.tail partition (_ < coll.head) quicksort(smaller) ++ coll.companion(coll.head) ++ quicksort(bigger) }
def mode [T : Ordering, CC[X] <: TraversableType[X,CC] : From[Nothing,T]#CanBuild] (coll: CC[T]): CC[T] = { val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq val max = grouped.map(_._2).max grouped.filter(_._2 == max).map(_._1)(breakOut)}
I guess it can still scare the unwary, but I think it truly is a major improvement. Can these minor additions be added to 2.8's library?
On Sat, Nov 14, 2009 at 6:34 PM, David Hall <dlwh@cs.berkeley.edu> wrote:
trait From[-Fr,-Elem] { type CanBuild[+To[Elem]] = CanBuildFrom[Fr,Elem,To[Elem]]}
type TraversableType[A, CC[T] <: Traversable[T] withTraversableLike[T,CC[T]] with GenericTraversableTemplate[T, CC]] = Traversable[A] with TraversableLike[A,CC[A]] with GenericTraversableTemplate[A, CC]
Then the two examples can be thus simplified:
def quicksort [T <% Ordered[T], CC[X] <: TraversableType[X,CC] : From[CC[T],T]#CanBuild] (coll: CC[T]): CC[T] = if (coll.isEmpty) { coll } else { val (smaller, bigger) = coll.tail partition (_ < coll.head) quicksort(smaller) ++ coll.companion(coll.head) ++ quicksort(bigger) }
def mode [T : Ordering, CC[X] <: TraversableType[X,CC] : From[Nothing,T]#CanBuild] (coll: CC[T]): CC[T] = { val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq val max = grouped.map(_._2).max grouped.filter(_._2 == max).map(_._1)(breakOut)}
I guess it can still scare the unwary, but I think it truly is a major improvement. Can these minor additions be added to 2.8's library?
On Sat, Nov 14, 2009 at 6:34 PM, David Hall <dlwh@cs.berkeley.edu> wrote:
Taking offlist to not pollute internals too much:
I can also do:
scala> trait From[-Fr,-Elem] { type CanBuild[+To] =
CanBuildFrom[Fr,Elem,To] }
defined trait From
scala> def foo[T:Ordering,CC[X] <: TraversableType[X,CC],
CR:From[CC[T],T]#CanBuild ](f: T, a: CC[T]) = null:CR
foo: [T,CC[X] <: TraversableType[X,CC],CR](f: T,a: CC[T])(implicit
evidence$1: Ordering[T],implicit evidence$2:
scala.collection.generic.CanBuildFrom[CC[T],T,CR])CR
Though 1) it may not actually work in reality and 2) it may not do
what you want anyway.