make clean

March 6, 2008

lazy sequences in scala

Filed under: Uncategorized — harshadrj @ 12:53 pm
Tags: ,

At work, some of us were discussing about lazy lists v/s iterators. I just tried a quick lazy list in scala, and it worked pretty well to my satisfaction.

class roleNumbers extends RandomAccessSeq[String] {

def length=10;
def apply(n:Int) = {println(“evalutaing ” + n); “role:” + n}


val xyz = new roleNumbers

// drop 8 elements, map the sequence, and then take first element
val one_element = xyz.drop(8).map(“rum ” + _)(0)

println (one_element)

The output :

evalutaing 8
rum role:8

The laziness is preserved across list operations which is a good thing.

In fact, I notice that Iterator trait and List trait have a similar interface, which reinforces my belief that they are pretty much the same, though usage semantics might be differ slightly.

I now need to figure out how to implement an efficient get_next_element kind of iterator in scala.



  1. Take a look at the Stream class, too.

    Comment by Tom — March 6, 2008 @ 11:13 pm | Reply

  2. Thanks for the pointer Tom

    I thought Stream only allowed an infinite stream, so it wouldn’t have a reverse function.

    But a closer look reveals that it does have a reverse function and a way to create Definite Streams.

    Comment by harshadrj — March 7, 2008 @ 7:36 pm | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at

%d bloggers like this: