Skip to content
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

parser, checker: check invalid lambda expr (fix #20414) #20461

Merged
merged 1 commit into from
Jan 10, 2024

Conversation

yuyi98
Copy link
Member

@yuyi98 yuyi98 commented Jan 10, 2024

This PR check invalid lambda expr (fix #20414).

  • Check invalid lambda expr.
  • Add test.
fn main() {
	x := 5
	f := if x == 5 { |x| x - 5 } else { |x| x }
	println(f(x))
}

PS D:\Test\v\tt1> v run .
tt1.v:3:19: error: lambda expressions are allowed only in places expecting function callbacks
    1 | fn main() {
    2 |     x := 5
    3 |     f := if x == 5 { |x| x - 5 } else { |x| x }
      |                      ~~~~~~~~~
    4 |     println(f(x))
    5 | }

Copy link
Member

@spytheman spytheman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent work.

@spytheman spytheman merged commit c1904ec into vlang:master Jan 10, 2024
54 checks passed
@yuyi98 yuyi98 deleted the check_lambda_expr branch January 10, 2024 14:23
@zeozeozeo
Copy link
Contributor

I think this should be allowed in the future, lambdas should act as functions.

For example, this is allowed:

import term

fn print_colored(is_red bool, text string) {
    color := if is_red { term.red } else { term.white }
    print(color(text))
}

but this is not:

import term

fn print_colored(is_red bool, text string) {
    color := if is_red { |text| term.red(text) } else { |text| term.white(text) }
    print(color(text))
}

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

Successfully merging this pull request may close these issues.

Cannot use closures as a final statement in an if/else block
3 participants