This page is no longer maintained — Please continue to the home page at www.scala-lang.org

lazy varargs?

2 replies
Landei
Joined: 2008-12-18,
User offline. Last seen 45 weeks 4 days ago.

Hi!

Just a small question: Wouldn't it make sense that varargs behave lazy? I
mean, maybe just a few elements from the sequence might be actually needed
inside the function. IMHO having them wrapped in a Stream instead of an
Array could be very useful.

Cheers,
Daniel

ewilligers
Joined: 2008-08-20,
User offline. Last seen 3 years 17 weeks ago.
Re: lazy varargs?

Landei wrote:
> Hi!
>
> Just a small question: Wouldn't it make sense that varargs behave lazy? I
> mean, maybe just a few elements from the sequence might be actually needed
> inside the function. IMHO having them wrapped in a Stream instead of an
> Array could be very useful.

Stream wouldn't make the first element lazy.

Note you can sometimes "cheat":-

class Wrapper(expression: => Int) {
def evaluate = expression
}

object Test {

implicit def int2Wrapper(expression: => Int) = new Wrapper(expression)

def f(seq: Wrapper*) {
println(seq(0).evaluate)
}

def main(args: Array[String]) {
f(32, 1/0)
}

}

32

Landei
Joined: 2008-12-18,
User offline. Last seen 45 weeks 4 days ago.
Re: lazy varargs?

Eric Willigers wrote:
>
> Landei wrote:
>> Hi!
>>
>> Just a small question: Wouldn't it make sense that varargs behave lazy? I
>> mean, maybe just a few elements from the sequence might be actually
>> needed
>> inside the function. IMHO having them wrapped in a Stream instead of an
>> Array could be very useful.
>
> Stream wouldn't make the first element lazy.
>
>
> Note you can sometimes "cheat":-
>
>
> class Wrapper(expression: => Int) {
> def evaluate = expression
> }
>
> object Test {
>
> implicit def int2Wrapper(expression: => Int) = new
> Wrapper(expression)
>
> def f(seq: Wrapper*) {
> println(seq(0).evaluate)
> }
>
> def main(args: Array[String]) {
> f(32, 1/0)
> }
>
> }
>
> 32
>

Thanks, that looks interesting. So maybe it would be a good idea to
generalize this technique and have a generic lazy Wrapper class (LazyCell?)
and an implicit conversion as part of the standard lib? I think this could
be very useful, not only for varargs.

Cheers,
Daniel

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland