com-lihaoyi / geny

Provides the geny.Generator data type, the dual to a scala.Iterator that can ensure resource cleanup

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Traversable view conversion

amasson88 opened this issue · comments

hi

Thanks for this nice library! Exactly what I was looking for :)

I have found a small issue. There is some implicit conversion in v0.1.2 from Traversable(View) that doesn't preserve laziness.

For example

  val source = new Traversable[String] {
      def foreach[U](f: String => U): Unit = {
        println("emit V1")
        f("V1")
        println("emit V2")
        f("V2")
        println("emit V3")
        f("V3")
      }
    }    
    val gen: Generator[String] = source.view    
    gen.foreach { x => println("foreach " + x) }

gives:

emit V1
emit V2
emit V3
foreach V1
foreach V2
foreach V3

As a workaround, something like this seems to work:

    def fromLazyTrav[T](trav: Traversable[T]) = new Generator[T] {
      import Generator._
      def generate(f: T => Action): Action = {
        trav.foreach { x =>
          val r = f(x)
          if (r == End) return End
        }
        Continue
      }
    }
...
    val gen = fromLazyTrav(source)
    gen.foreach { x => println("foreach " + x) }

It gives:

emit V1
foreach V1
emit V2
foreach V2
emit V3
foreach V3

Would it be possible to preserve laziness by default?

thanks
Arnaud

Views are deprecated so probably not gonna bother