-
Notifications
You must be signed in to change notification settings - Fork 17.6k
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
proposal: spec: lightweight anonymous function syntax #21498
Comments
I'm sympathetic to the general idea, but I find the specific examples given not very convincing: The relatively small savings in terms of syntax doesn't seem worth the trouble. But perhaps there are better examples or more convincing notation. (Perhaps with the exception of the binary operator example, but I'm not sure how common that case is in typical Go code.) |
Please no, clear is better than clever. I find these shortcut syntaxes
impossibly obtuse.
…On Fri, 18 Aug 2017, 04:43 Robert Griesemer ***@***.***> wrote:
I'm sympathetic to the general idea, but I find the specific examples
given not very convincing: The relatively small savings in terms of syntax
doesn't seem worth the trouble. But perhaps there are better examples or
more convincing notation.
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
<#21498 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/AAAcAxlgwt-iPryyY-d5w8GJho0bY9bkks5sZInfgaJpZM4O6pBB>
.
|
I think this is more convincing if we restrict its use to cases where the function body is a simple expression. If we are required to write a block and an explicit Your examples then become
The syntax is something like
This may only be used in an assignment to a value of function type (including assignment to a parameter in the process of a function call). The number of identifiers must match the number of parameters of the function type, and the function type determines the identifier types. The function type must have zero results, or the number of result parameters must match the number of expressions in the list. The type of each expression must be assignable to the type of the corresponding result parameter. This is equivalent to a function literal in the obvious way. There is probably a parsing ambiguity here. It would also be interesting to consider the syntax
as in
|
A few more cases where closures are commonly used. (I'm mainly trying to collect use cases at the moment to provide evidence for/against the utility of this feature.) |
I actually like that Go doesn't discriminate longer anonymous functions, as Java does. In Java, a short anonymous function, a lambda, is nice and short, while a longer one is verbose and ugly compared to the short one. I've even seen a talk/post somewhere (I can't find it now) that encouraged only using one-line lambdas in Java, because those have all those non-verbosity advantages. In Go, we don't have this problem, both short and longer anonymous functions are relatively (but not too much) verbose, so there is no mental obstacle to using longer ones too, which is sometimes very useful. |
The shorthand is natural in functional languages because everything is an expression and the result of a function is the last expression in the function's definition. Having a shorthand is nice so other languages where the above doesn't hold have adopted it. But in my experience it's never as nice when it hits the reality of a language with statements. It's either nearly as verbose because you need blocks and returns or it can only contain expressions so it's basically useless for all but the simplest of things. Anonymous functions in Go are about as close as they can get to optimal. I don't see the value in shaving it down any further. |
It's not the Simply allowing the function literals to elide unambiguous types would go a long way. To use the Cap'n'Proto example: s.Write(ctx, func(p) error { return p.SetData([]byte("Hello, ")) }) |
Yes, it's the type declarations that really add noise. Unfortunately, "func (p) error" already has a meaning. Perhaps permitting _ to substitute in for an inferenced type would work? s.Write(ctx, func(p _) _ { return p.SetData([]byte("Hello, ")) }) I rather like that; no syntactic change at all required. |
I do not like the stutter of _. Maybe func could be replaced by a keyword that infers the type parameters: |
Is this actually a proposal or are you just spitballing what Go would look like if you dressed it like Scheme for Halloween? I think this proposal is both unnecessary and in poor keeping with the language's focus on readability. Please stop trying to change the syntax of the language just because it looks different to other languages. |
I think that having a concise anonymous function syntax is more compelling in other languages that rely more on callback-based APIs. In Go, I'm not sure the new syntax would really pay for itself. It's not that there aren't plenty of examples where folks use anonymous functions, but at least in the code I read and write the frequency is fairly low. |
To some extent, that is a self-reinforcing condition: if it were easier to write concise functions in Go, we may well see more functional-style APIs. (Whether that is a good thing or not, I do not know.) I do want to emphasize that there is a difference between "functional" and "callback" APIs: when I hear "callback" I think "asynchronous callback", which leads to a sort of spaghetti code that we've been fortunate to avoid in Go. Synchronous APIs (such as |
I would just like to chime in here and offer a use case where I have come to appreciate the consider:
Now imagine we are trying to curry a value into a Not convinced? Didn't think so. I love go's simplicity too and think it's worth protecting. Another situation that happens to me a lot is where you have and you want to now curry the next argument with currying. now you would have to change If there was an arrow syntax you would simply change |
@neild whilst I haven't contributed to this thread yet, I do have another use case that would benefit from something similar to what you proposed. But this comment is actually about another way of dealing with the verbosity in calling code: have a tool like Taking your example: func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
} If we assume we had typed: var _ = compute(
^ with the cursor at the position shown by the var _ = compute(func(a, b float64) float64 { })
^ That would certainly cover the use case I had in mind; does it cover yours? |
Code is read much more often than it is written. I don't believe saving a little typing is worth a change to the language syntax here. The advantage, if there is one, would largely be in making code more readable. Editor support won't help with that. A question, of course, is whether removing the full type information from an anonymous function helps or harms readability. |
I don't think this kind of syntax reduces readability, almost all modern programming languages have a syntax for this and thats because it encourages the use of functional style to reduce the boilerplate and make the code clearer and easier to maintain. It's a great pain to use anonymous functions in golang when they are passed as parameters to functions because you have to repeat yourself typing again the types that you know you must pass. |
I support the proposal. It saves typing and helps readability.My use case, // Type definitions and functions implementation.
type intSlice []int
func (is intSlice) Filter(f func(int) bool) intSlice { ... }
func (is intSlice) Map(f func(int) int) intSlice { ... }
func (is intSlice) Reduce(f func(int, int) int) int { ... }
list := []int{...}
is := intSlice(list) without lightweight anonymous function syntax: res := is.Map(func(i int)int{return i+1}).Filter(func(i int) bool { return i % 2 == 0 }).
Reduce(func(a, b int) int { return a + b }) with lightweight anonymous function syntax: res := is.Map((i) => i+1).Filter((i)=>i % 2 == 0).Reduce((a,b)=>a+b) |
The lack of concise anonymous function expressions makes Go less readable and violates the DRY principle. I would like to write and use functional/callback APIs, but using such APIs is obnoxiously verbose, as every API call must either use an already defined function or an anonymous function expression that repeats type information that should be quite clear from the context (if the API is designed correctly). My desire for this proposal is not even remotely that I think Go should look or be like other languages. My desire is entirely driven by my dislike for repeating myself and including unnecessary syntactic noise. |
In Go, the syntax for function declarations deviates a bit from the regular pattern that we have for other declarations. For constants, types, variables we always have:
For example:
In general, the type can be a literal type, or it can be a name. For functions this breaks down, the type always must be a literal signature. One could image something like:
where the function type is given as a name. Expanding a bit, a BinaryOp closure could then perhaps be written as
which might go a long way to shorter closure notation. For instance:
The main disadvantage is that parameter names are not declared with the function. Using the function type brings them "in scope", similar to how using a struct value Also, this requires an explicitly declared function type, which may only make sense if that type is very common. Just another perspective for this discussion. |
Readability comes first, that seems to be something we can all agree on. But that said, one thing I want to also chime in on (since it doesn't look like anyone else said it explicitly) is that the question of readability is always going to hinge on what you're used to. Having a discussion as we are about whether it hurts or harms readability isn't going to get anywhere in my opinion. @griesemer perhaps some perspective from your time working on V8 would be useful here. I (at least) can say I was very much happy with javascript's prior syntax for functions ( But, all the same, the arrow syntax happened and I accepted it because I had to. Today, though, having used it a lot more and gotten more comfortable with it, I can say that it helps readability tremendously. I used the case of currying (and @hooluupog brought up a similar case of "dot-chaining") where a lightweight syntax produces code that is lightweight without being overly clever. Now when I see code that does things like What I'm saying is: this discussion boils down to:
The best thing we can do is provide more use-cases. |
In response to @dimitropoulos's comment, here's a rough summary of my view: I want to use design patterns (such as functional programming) that would greatly benefit from this proposal, as their use with the current syntax is excessively verbose. |
@dimitropoulos I've been working on V8 alright, but that was building the virtual machine, which was written in C++. My experience with actual Javascript is limited. That said, Javascript is a dynamically typed language, and without types much of the typing goes away. As several people have brought up before, a major issue here is the need to repeat types, a problem that doesn't exist in Javascript. Also, for the record: In the early days of designing Go we actually looked at arrow syntax for function signatures. I don't remember the details but I'm pretty sure notation such as
was on the white board. Eventually we dropped the arrow because it didn't work that well with multiple (non-tuple) return values; and once the But having closures in a performant, general purpose language opened the doors to new, more functional programming styles. Now, 10 years down the road, one might look at it from a different angle. Still, I think we have to be very careful here to not create special syntax for closures. What we have now is simple and regular and has worked well so far. Whatever the approach, if there's any change, I believe it will need to be regular and apply to any function. |
Note that for parameter lists and
The If we address the problem of literals, then I believe the problem of declarations becomes trivial. For declarations of constants, variables, and now types, we allow (or require) an
The expression after the Note that the difference between a Examples Consider this function declaration accepted today: func compute(f func(x, y float64) float64) float64 { return f(3, 4) } We could either retain that (e.g. for Go 1 compatibility) in addition to the examples below, or eliminate the For various Rust-like:
Admits any of: func compute = |f func(x, y float64) float64| { f(3, 4) } func compute(func (x, y float64) float64) float64 = |f| { f(3, 4) } func (
compute = |f func(x, y float64) float64| { f(3, 4) }
) func (
compute(func (x, y float64) float64) float64 = |f| { f(3, 4) }
) Scala-like:
Admits any of: func compute = (f func(x, y float64) float64) => f(3, 4) func compute(func (x, y float64) float64) float64 = (f) => f(3, 4) func (
compute = (f func(x, y float64) float64) => f(3, 4)
) func (
compute(func (x, y float64) float64) float64 = (f) => f(3, 4)
) Lambda-calculus-like:
Admits any of: func compute = λf func(x, y float64) float64.f(3, 4) func compute(func (x, y float64) float64) float64) = λf.f(3, 4) func (
compute = λf func(x, y float64) float64.f(3, 4)
) func (
compute(func (x, y float64) float64) float64) = λf.f(3, 4)
) Haskell-like:
func compute = \f func(x, y float64) float64 -> f(3, 4) func compute(func (x, y float64) float64) float64) = \f -> f(3, 4) func (
compute = \f func(x, y float64) float64 -> f(3, 4)
) func (
compute(func (x, y float64) float64) float64) = \f -> f(3, 4)
) C++-like:
Admits any of: func compute = [f func(x, y float64) float64] { f(3, 4) } func compute(func (x, y float64) float64) float64) = [f] { f(3, 4) } func (
compute = [f func(x, y float64) float64] { f(3, 4) }
) func (
compute(func (x, y float64) float64) float64) = [f] { f(3, 4) }
) Personally, I find all but the Scala-like variants to be fairly legible. (To my eye, the Scala-like variant is too heavy on parentheses: it makes the lines much more difficult to scan.) |
Personally I'm mainly interested in this if it lets me omit the parameter and result types when they can be inferred. I'm even fine with the current function literal syntax if I can do that. (This was discussed above.) Admittedly this goes against @griesemer 's comment. |
The syntax I'm preferring the most is exactly the same as the normal syntax except the types are inferred, but that syntax is not an option because of #21498 (comment). It's also the most preferred option by the community in #21498 (comment). The issue is that we need a slight difference, one character or so, so that existing code don't break. One way would be to use |
Maybe the I think this syntax was first suggested in #21498 (comment) in 2017. Cases like #21498 (comment) by @DeedleFake and #21498 (comment) by @bradfitz would become a good deal less painful if type names could simply be replaced by And it doesn't shut the door for other solutions. If users gain some experience with it and still think it's too verbose for cases like |
I don't know why I didn't quite get the templating algebra necessary to allow arbitrary covariance between the different parameters and the return. Phew. Is it too late to just ask for generic, anonymous functions instead? Just kidding....I think... |
Although I do not agree with it very positively, I think that abbreviated notation could be introduced only when the body of the function can be written in a single expression.
In order not to add new tokens, I have chosen = for the symbol. It also looks like type aliases. |
After introduce iterator, lack of simplified function syntax makes code worse, think such case: without simplified syntax: x := iter.Filter(
iter.Map(s.Exprs, func(t *expr.Expression) result.Result[*value.Value] {
return e.eval(ctx, t)
}),
func(r result.Result[*value.Value]) bool {
return r.IsOk()
},
) with a possible simplified syntax: x := iter.Filter(iter.Map(s.Exprs, |t| e.eval(ctx, t)), |r| r.IsOk()) |
Also for writing a new iterator, a short function is IMO an improvement: func Count() iter.Seq[int] {
return (yield) => {
n := 0
for {
if !yield(n) {
return
}
}
}
} The noise of And what if |
Having recently written a dozen or so iterators to play with the feature I certainly agree that they are an excellent example of why sometimes you want the short syntax but with a full block instead of just an expression. I would be quite happy with |
@SuperWindCloud Golang is not standing still - it's simply not jumping the gun. It is trivial to add some lightweight function syntax, many different approaches have been proposed in this tread, and some have even be implemented as prototypes. A |
I still agree with the original comment from @davecheney
Eliding all the types makes the code harder to read and understand. It might not be "pretty" or "neat" to have all those types and syntax in there, and it might take longer to write (though we do have auto-completion in editors) but the code can then be read and understood. I have heard it said that code is written once and then read many times. Go's syntax is a breath of fresh air from this perspective and I hope we don't lose that characteristic to save a few keystrokes or "reduce noise". |
We've had type inference in Go since release with In a similar way we can all see what I think most of us understand the potential value for this anyway--I just want to make it clear that this proposal helps with readability and is not just to "save a few keystrokes." Concise isn't necessarily obfuscated; in many cases it's the reverse. |
@brightpuddle I agree. Type inference increases the signal to noise ratio, in my humble opinion. Being able to elide the type annotations in lambdas seems to me to bring the code that matters to the forefront and make data pipelining and transformations more glanceable. |
@tooolbox like @brightpuddle says there's already inference everywhere in golang. You (and the rest of the community) are just deciding on when inference improves readability vs when it doesn't. This type of syntax is very useful and easier to read and can reduce noise and can be more clear when done carefully. Conciseness while being careful not to be too terse is one of the ways to make writing anything more understandable. The main argument that most people are making here isn't that it's 'too much code' but that it's code that makes the expression of common programming patterns less readable and less understandable because of the associated noise. |
That's not really true. Before generics we had type inference for constants and for variables declaration. With generics type inference for generic instantiation was added. That is all.
For this to work the compiler needs to:
Partially determined types can propagate indefinitely deep, of course. Also, consider this:
is this supposed to be valid? |
I would expect the
In contrast,
|
Good for you but note that almost everyone that's advocating for lightweight anonymous functions in this issue, and writes example code, writes something that needs fairly complicated type inference to work. |
@aarzilli I'm not claiming that it doesn't take work, and I'm certainly not claiming that it won't be hard. How difficult it'll be is certainly something that should go into the decision whether or not to adopt it. I'm simply saying that the argument from @tooolbox around inference ignores the fact that the language already does it in places people find useful and don't introduce readability issues... and I doubt many people want to type all their vars. I guess more specifically my point is that "more text" doesn't make something easier to read when the information is redundant in context like it can be in a ton of these cases.
Plenty of strongly typed languages (C#, Rust) support eliding types when possible and including them when there's ambiguity. I don't see why @neild's point conflicts with that but a bit of lookahead would be nice as a QOL on his map example. All tradeoffs that need to be decided on but I don't see the conflict you're seeing. |
Wait. Does this mean...? Is this just bookkeeping, or...? |
Drat. I got all excited for nothing! Thanks for the explanation/link, @aarzilli. |
|
Many languages provide a lightweight syntax for specifying anonymous functions, in which the function type is derived from the surrounding context.
Consider a slightly contrived example from the Go tour (https://tour.golang.org/moretypes/24):
Many languages permit eliding the parameter and return types of the anonymous function in this case, since they may be derived from the context. For example:
I propose considering adding such a form to Go 2. I am not proposing any specific syntax. In terms of the language specification, this may be thought of as a form of untyped function literal that is assignable to any compatible variable of function type. Literals of this form would have no default type and could not be used on the right hand side of a
:=
in the same way thatx := nil
is an error.Uses 1: Cap'n Proto
Remote calls using Cap'n Proto take an function parameter which is passed a request message to populate. From https://github.com/capnproto/go-capnproto2/wiki/Getting-Started:
Using the Rust syntax (just as an example):
Uses 2: errgroup
The errgroup package (http://godoc.org/golang.org/x/sync/errgroup) manages a group of goroutines:
Using the Scala syntax:
(Since the function signature is quite small in this case, this might arguably be a case where the lightweight syntax is less clear.)
The text was updated successfully, but these errors were encountered: