logo       

Re: Empty Iterators: msg#00443

lang.scala

Subject: Re: Empty Iterators



On 1/27/07, Miles Sabin <miles@xxxxxxxxxxxxxx> wrote:
Burak Emir wrote,
> Iterator[+a] is covariant in a. That means that X<:Y implies
> Iterator[X]<:Iterator[Y].
> And since Nothing <: T for any T, you have Iterator[Nothing] <:
> Iterator[T] for any T you can think of, even if it is a type
> parameter A.
>
> In short, having an empty iterator of type Iterator[Nothing] is just
> as good as having one of type Iterator[A].

I don't think it is in the example I gave,

  class DisjointUnion[A](family : List[Set[A]])
    extends Set[A]
  {
    def elements =
      family.foldLeft(Iterator.empty)((i, s) => i ++ s.elements)
  }

gives me the compiler error,

  type mismatch;
     found   : scala.Iterator [A]
     required: scala.Iterator[scala.Nothing]

haha the  problem is the other way round: the compiler complains that s.elements is scala.Iterator[A], which is too coarse for the fold, which it has cleverly inferred to return an Iterator[Nothing].

I could do this,

    def elements =
      family.foldLeft(Iterator.empty.asInstanceOf [Iterator[A]])(
        (i, s) => i ++ s.elements)

but that's pretty ugly. Or I can add the following,

you could also just ascribe the type (Iterator.empty:Iterator[A])...

  object Collections
  {
    def emptyIterator[A] : Iterator[A] = Iterator.empty
  }

...or use a "val" here

and do this,

  def elements =
    family.foldLeft(Collections.emptyIterator[A])(
      (i, s) => i ++ s.elements)

but it'd nicer if emptyIterator (or something equivalent) lived on
scala.Iterator.

it would only be needed for  these type inference to work...
it's not nice to define a def that returns the exact same thing as the val, only with coarser type.
I think type ascription is a better solution. You could also give a type argument to foldLeft, and the problem would go away, too.

cheers,
Burak

--
Burak Emir
Research Assistant / PhD Candidate
Programming Methods Group
EPFL, 1015 Lausanne, Switzerland
http://lamp.epfl.ch/~emir
<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise