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

List and filter

2 replies
Tim Williams
Joined: 2010-05-05,
User offline. Last seen 42 years 45 weeks ago.

I came upon this bit of code today:

val params = post.request.getParameterNames //this is definitely ==
("p1", "p2", "p3")
val missing = List("p1", "p2", "p3") filterNot (params.toList.contains(_))

$missing always contains every parameter as missing.

I changed it to the toList outside of the filter:

val params = post.request.getParameterNames.toList
val missing = List("p1", "p2", "p3") filterNot (params.contains(_))

$missing is properly empty.

Clearly the former seems improper/inefficient, but it's not clear why
it's incorrect?

Thanks,
--tim

dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: List and filter

On Tue, Jan 24, 2012 at 16:01, Tim Williams wrote:
> I came upon this bit of code today:
>
> val params = post.request.getParameterNames //this is definitely ==
> ("p1", "p2", "p3")
> val missing = List("p1", "p2", "p3") filterNot (params.toList.contains(_))
>
> $missing always contains every parameter as missing.
>
> I changed it to the toList outside of the filter:
>
> val params = post.request.getParameterNames.toList
> val missing = List("p1", "p2", "p3") filterNot (params.contains(_))
>
> $missing is properly empty.
>
> Clearly the former seems improper/inefficient, but it's not clear why
> it's incorrect?

I'd wager "getParameterNames" is returning an Iterator, which gets
spent on the first call to "params.contains". Mmmm. But that would
remove at least p1...

So, *what* is the type returned by getParameterNames?

Tim Williams
Joined: 2010-05-05,
User offline. Last seen 42 years 45 weeks ago.
Re: List and filter

On Tue, Jan 24, 2012 at 2:31 PM, Daniel Sobral wrote:
> On Tue, Jan 24, 2012 at 16:01, Tim Williams wrote:
>> I came upon this bit of code today:
>>
>> val params = post.request.getParameterNames //this is definitely ==
>> ("p1", "p2", "p3")
>> val missing = List("p1", "p2", "p3") filterNot (params.toList.contains(_))
>>
>> $missing always contains every parameter as missing.
>>
>> I changed it to the toList outside of the filter:
>>
>> val params = post.request.getParameterNames.toList
>> val missing = List("p1", "p2", "p3") filterNot (params.contains(_))
>>
>> $missing is properly empty.
>>
>> Clearly the former seems improper/inefficient, but it's not clear why
>> it's incorrect?
>
> I'd wager "getParameterNames" is returning an Iterator, which gets
> spent on the first call to "params.contains". Mmmm. But that would
> remove at least p1...

Oh dear, how embarrassing. Yep, its a Java enumerator-> Scala
iterator:( I missed that it was n-1 elements.

Thanks,
--tim

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