Skip to content

Require case prefix for patterns in for-comprehension generators #5511

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
propensive opened this issue Nov 24, 2018 · 6 comments
Closed

Require case prefix for patterns in for-comprehension generators #5511

propensive opened this issue Nov 24, 2018 · 6 comments

Comments

@propensive
Copy link
Contributor

A common beginners' mistake when using for-comprehensions is to write a pattern on the left-side of a generator, and to not realize that it desugars to filter/withFilter.

I propose that this behavior should be supported only if the patter is prefixed with the keyword case, for example,

def collect(xs: List[Option[Int]]) = for {
  case Some(i) <- xs
} yield i

This would be a compile error:

def collect(xs: List[Option[Int]]) = for { Some(i) <- xs } yield i
@dwijnand
Copy link
Member

Using case makes it look like it'll match error.

What about if? Then it's obviously like other if filters. (Also it's similar to Rust's if let.)

@He-Pin
Copy link
Contributor

He-Pin commented Nov 24, 2018

image

def collect(xs: List[Option[Int]]) = for {
  case Some(i) <- xs
} yield i

and with no error

def collect(xs: List[Option[Int]]) = for {
  ifcase Some(i) <- xs
} yield i

@lihaoyi
Copy link
Contributor

lihaoyi commented Nov 24, 2018

duplicate of #2578

@DavidGregory084
Copy link

See also https://github.com/oleg-py/better-monadic-for/blob/master/README.md which changes the desugaring to use map and match

@propensive
Copy link
Contributor Author

@dwijnand No strong feelings either way in using case or if. The former does certainly cause a potential match error everywhere else, so that might be worth keeping as a universal truth.

@smarter
Copy link
Member

smarter commented Nov 24, 2018

So there's been a lot of proposals related to improving for-comprehensions, but it seems like there's just no one working on Dotty currently who's motivated enough to lead the redesign. To move forward, I suggest people who are interested in the topic build consensus and collaboratively write a SIP. Once we have an accepted SIP, the implementation should be easy. Therefore, I'm going to close this and redirect people to https://contributors.scala-lang.org/t/making-for-simpler-and-more-regular/2160 where the discussion has already started.

@smarter smarter closed this as completed Nov 24, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants