Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement lazy sequence (iterable) in scala?

Tags:

yield

scala

I want to implement a lazy iterator that yields the next element in each call, in a 3-level nested loop.

Is there something similar in scala to this snippet of c#:

foreach (int i in ...)
    {
        foreach (int j in ...)
        {
            foreach (int k in ...)
            {
                 yield return do(i,j,k);
            }
        }
    }

Thanks, Dudu

like image 865
duduamar Avatar asked Dec 22 '10 16:12

duduamar


People also ask

Is Scala iterator lazy?

Unlike operations directly on a concrete collection like List , operations on Iterator are lazy.

What is iterable in Scala?

Iterable: A base trait for iterable collections. This is a base trait for all Scala collections that define an iterator method to step through one-by-one the collection's elements.

How to define iterator in Scala?

It provide us hasNext() and next() method to work with collection elements. The basic syntax to define the iterate in scala is as follows; valiterate_name = Iterator(value1, value2, value3, so on ....) In this way, we can define an iterate in scala.

What is true about iterators in Scala?

An iterator is not a collection, but rather a way to access the elements of a collection one by one. The two basic operations on an iterator it are next and hasNext . A call to it.


1 Answers

You can use a Sequence Comprehension over Iterators to get what you want:

for {
    i <- (1 to 10).iterator
    j <- (1 to 10).iterator
    k <- (1 to 10).iterator
} yield doFunc(i, j, k)

If you want to create a lazy Iterable (instead of a lazy Iterator) use Views instead:

for {
    i <- (1 to 10).view
    j <- (1 to 10).view
    k <- (1 to 10).view
} yield doFunc(i, j, k)

Depending on how lazy you want to be, you may not need all of the calls to iterator / view.

like image 183
Antony Perkov Avatar answered Oct 24 '22 22:10

Antony Perkov