for comprehensions and patterns

View: New views
3 Messages — Rating Filter:   Alert me  

for comprehensions and patterns

by Dimitris Andreou :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi all,

Reading Programming in Scala, I see that in for comprehensions, the
left part of a generator "pat <- expr" is really a pattern, and when
the pattern is not matched, the element is ignored.

So I tried this:

val list = List(1, "2", 3, "4")

for ((x: String) <- list) println(x)

<console>:6: error: type mismatch;
 found   : (String) => Unit
 required: (Any) => Unit
       for ((x: String) <- list) println(x)
            ^

While this (equivalent?) works fine:

list foreach {_ match {
  case x: String => println(x)
  case _ =>
}}

This is on 2.7.5.

So what's up here? Isn't (x: String) a valid pattern, indicating that
x must be of type String? It would really be nice if patterns worked
the same in all cases, and I understand that this was the intention,
so is this a bug? Or something I misunderstood?

Regards,
Dimitris

Re: for comprehensions and patterns

by Paul Phillips-3 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


On Sat, Oct 31, 2009 at 07:07:41PM +0200, Jim Andreou wrote:
> So what's up here? Isn't (x: String) a valid pattern, indicating that
> x must be of type String? It would really be nice if patterns worked
> the same in all cases, and I understand that this was the intention,
> so is this a bug?

When you ask yourself that you might also try asking mr. trac:

  https://lampsvn.epfl.ch/trac/scala/ticket/900

...along with several closed duplicates.

--
Paul Phillips      | A national political campaign is better than the
Stickler           | best circus ever heard of, with a mass baptism and
Empiricist         | a couple of hangings thrown in.
pp: i haul pills   |     -- H. L. Mencken

Re: for comprehensions and patterns

by Dimitris Andreou :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Oh, thanks Paul! Apparently I wasn't feeling too lucky. I'll build a
closer relationship with this trac guy from now on :)

2009/10/31 Paul Phillips <paulp@...>:

>
> On Sat, Oct 31, 2009 at 07:07:41PM +0200, Jim Andreou wrote:
>> So what's up here? Isn't (x: String) a valid pattern, indicating that
>> x must be of type String? It would really be nice if patterns worked
>> the same in all cases, and I understand that this was the intention,
>> so is this a bug?
>
> When you ask yourself that you might also try asking mr. trac:
>
>  https://lampsvn.epfl.ch/trac/scala/ticket/900
>
> ...along with several closed duplicates.
>
> --
> Paul Phillips      | A national political campaign is better than the
> Stickler           | best circus ever heard of, with a mass baptism and
> Empiricist         | a couple of hangings thrown in.
> pp: i haul pills   |     -- H. L. Mencken
>