Lambda Support
V is a concise and elegant language, and I think a syntax for lambda expressions could go along with the spirit of V. A lambda could be declared just like a function but without a name:
ints := [1, 2, 3]
doubled_ints := ints.map(fn (x int) {
return x * 2
})
However, lambdas would have some additional convinces compared to regular functions. Target Typing would allow the lambda to drop the types on it's parameters.
doubled_ints := ints.map(fn (x) { return x * 2 })
Furthermore, if the lambda consists of a single return statement, the braces may be emitted and the return will be implicit:
doubled_ints := ints.map(fn (x) x * 2)
If the lambda doesn't take any parameters, the parens after fn may be omitted:
repeat(3, fn {
println("Lambdas are awesome!")
})
The implicit return and parameterless fn could be combined:
repeat(3, fn println("Lambdas are awesome!"))
Closure could be implemented once V is more mature. For now, the ability to create anonymous functions would be a huge help to V programmers seeking a more functional style.
Hi,
Thanks. This was briefly discussed here:
https://github.com/vlang/v/issues/283
The syntax I'm considering is
doubled_ints := ints.map(fn (x) { return x * 2 })
==>
doubled_ints := ints.map(_ * 2)
One thing I'm worried about is that it's very easy easy to write unreadable code with complex nested maps.
I'm not sure what is the best way to prevent this.
_ * 2
Summarizing my comment from that issue:
That lambda syntax is not very general, it doesn't allow multiple lambda arguments. _ is the only clue in an expression that it's a lambda, it's quite cryptic - the argument doesn't always come first: 1 / _.
I suggest fn x! + y! if we want very short syntax. Other sigils can work instead of x!, e.g. \x, which Haskell uses for lambda parameters.
I believe that a explicit declaration of the lambda but implicit parameter inference could work together:
The compact style of _ parameters can be confusing:
doubled_ints := ints.map(_ * 2) // What does _ mean? Is it a number? A variable?
However, a fn keyword could make this more clear:
doubled_ints := ints.map(fn _ * 2) //Oh, _ is part of a function
Parameters could be added at will:
doubled_ints := ints.map(fn (x) x * 2)
However, implicit return would aid in increasing readability
It's often good to have meaningful names for parameters to help the reader, even for lambdas. What if any single underscore prefixed identifiers _ident after fn are inferred parameters:
odd := container.filter(
fn _elem & 1)
sum := container.reduce(
fn _total + _elem)
container.sort(
fn _a < _b)
doubled_ints := ints.map({ return it * 2 }) like kotlin or doubled_ints := ints.map({ return $0 * 2 }) like swift
So, considering all your opinions, I think the syntax for lambda expressions should follow the following rules:
- When a
fnkeyword is found in a value position (ie. right-hand side of assignment, inside a parameter list, aconstdeclaration) it is inferred to be a lambda. Lambdas are compile-time anonymous functions, which are given names for use at runtime. Lambdas create their own independent scope, and do not have closure. This means that lambdas do not capture their parent function's scopes. However, they can accessconsts , imported modules, and other top-level constructs (ie. functions, structs). The syntax of a lambda follows the following rules:
Lambdas in V would support Target Typing. Ex:
fn map(arr int[], func fn (int) int) int[] {
// Do the mapping
}
And later:
map([1, 2, 3], fn (x /* int type inferred */) /* return type int inferred */ { return x * 2 })
Rule 1. All lambdas are prefixed with fn. Without the fn keyword, no lambda is inferred.
Rule 2. Lambdas follow the syntax regulations for normal functions, with the exception that the alphanumeric identifier after fn is absent. However, lambdas allow certain syntactic shorthands to increase readability.
Rule 3. Lambdas that take no parameters may omit the () after fn.
Ex:
repeat(3, fn {
println("Hello World!")
})
Rule 4. Lambdas that consist of only one return statement may omit the return and the curly braces after the parameter list:
doubled_ints := ints.map(fn (x) x * 2)
Rule 5: Rule 3 and Rule 4 may be used together:
list_of_threes := ints.map(fn 3)
Rule 6: Marking a valid name with a ! at its end inside a lambda creates an inferred parameter. This inferred parameter is then (at compile-time) extracted into the parameter list. Two identical names marked with ! at their end are considered to refer to the same parameter. Since inferred parameters don't appear in the function's parameter list, they can be used in synergy with Rule 5:
doubled_ints := ints.map(fn x! * 2)
total := ints.reduce(fn total! + value!)
Translation to V (as of now): Currently V offers no native support for lambdas. Lambdas without closure, however, would not require any modifications to the V Runtime (assuming V supports passing functions as parameters). At compile-time, V's compiler could extract lambdas into their own functions: If the source code was:
fn main(){
products := zipWith(fn x! * y!, [1, 2, 3], [4, 5, 6]) // ==> [4, 10, 18]
}
At compile time it would become:
fn lambda_1 /*unique name generated by compiler*/ (x int, y int) int {
return x * y;
}
fn main(){
products := zipWith(lambda_1, [1, 2, 3], [4, 5, 6]) // ==> [4, 10, 18]
}
Tell me what you think of this "proposal" for V lambda expressions.
V is a simple language. You just introduced 6 extra rules that have to be learned.
Rule 3 means that there are now 2 different ways to write lambdas without parameters. One of V's main philosophies is to have only one way of doing things.
So ideally, no new syntax would have to be introduced at all, just like in Go:
repeat(3, fn() {
println('Lambdas are awesome!')
})
doubled_ints := ints.map(fn(n int) int { return n * 2 })
map, filter, etc often have one liners, so I propose the _ syntax similar to Scala's, that only works with one liners:
doubled_ints := ints.map(_ * 2)
@ntrel It won't be possible to declare a variable named _, so it won't be confusing.
For multiple arguments the traditional syntax will be used with full types specified. I think omitting the type is only readable when there's only one argument, the function is simple, and it's clear what the type is, like in the map example above.
I agree syntax rules should be simple. _ is a special syntax for lambdas that only take one unnamed argument. Instead of this special case, let's have a more useful general one:
fn (parameters) expression
This cuts out the return keyword and the noise of the braces, but still supports naming parameters and more than one parameter. It is also much closer to anonymous function syntax than just _ * 2, so it will be intuitive to anyone reading the code who is familiar with lambdas from many other languages. _ would not be familiar, they'd have to Google vlang underscore.
Multiple parameter lambdas are very common for any function that provides custom ordering, sort, merge etc.
For multiple arguments the traditional syntax will be used with full types specified
- If parameters are named, types are less needed.
- I'm not aware of any languages with generics that require types for lambda parameters. It's fine to require types for now, but later we should have inference for ease of use and easier reading of code.
it's very easy easy to write unreadable code with complex nested maps.
_ lambda syntax can't support nesting, my proposed general lambda syntax does:
// get strings that have whitespace
r := my_strings.filter(fn (s) s.can_find(
fn (c) c.is_white()))
@medvednikov makes a convincing argument. There should only be one way of doing things. V should support support lambdas that look just like functions without names. However, I still feel like the _ character is a little vague. An earlier proposal suggested something likes Swift's $0 inferred parameters. Perhaps the $num pattern could work? It allows flexible one liners, but also is more explicit than _. So we would have normal fns without names for lambdas, and then $nums for short one-liners. What do you think (I feel it is a balance between implicit and explicit)?
@medvednikov how would you feel about something like & instead of _? The main problem I see with the underscore is that it's easy to miss, whereas an ampersand is a little easier to spot. Your example would then become this:
doubled_ints := ints.map(& * 2)
It also has a familiarity to it for anyone that's used Ruby or SASS (maybe others too, idk).
Why do not just use the same syntax that it is used in named fn?. Using any hidden trick like _, & or 'it' adds confusion to the reader, limits parameters to 1 and does not support nested lambdas.
You could try to remove {} as @N8python suggested to make it "cleaner" when it is a one liner:
doubled_ints := ints.map(fn (x) x * 2)
One thing to discuss should be if the return type is mandatory or always infered.
I agree with @aguspiza that the best syntax for one liners would be fn ([params]) [return value]. It's clear, explicit, and easier to understand than _ and &. The pattern fn ([params]) [return value] is actually implemented in Douglas Crockford's transpiled language Neo. As for return value inference, for a one liner it shouldn't be any harder than inferring a type for a variable.
@aguspiza the point behind the shorter syntax is just that, it's shorter and more concise for simple operations. I know in Ruby I use it all the time for Array#map. Instead of doing this arr.map { |i| i.inc } you can do arr.map(&.inc).
I know some people aren't fans of syntactic sugar like that, but it does make things a bit more concise. Of course we should still have a full lambda syntax, and for that I agree that the ints.map(fn (x) x * 2) syntax makes the most sense.
Using any hidden trick like _, & or 'it' adds confusion to the reader
It's used in many popular languages with functional features like Scala, Swift, Ruby, Kotlin. I wouldn't call it confusing.
Of course we should still have a full lambda syntax, and for that I agree that the ints.map(fn (x) x * 2) syntax makes the most sense.
So now we have 3 lambda syntaxes :)
@medvednikov 3? What's the third? I only see the short syntax and the long syntax
@watzon
- ints.map(fn (x int) { return x * 2 })
- ints.map(fn (x) x * 2)
- ints.map(& * 2)
I feel like lambda syntax is very complicated as it is implemented in so many different ways. Ie. Javascript has 6 different ways of writing the same line of code for doubling all ints in an array:
ints.map(x => x * 2);
ints.map((x) => x * 2);
ints.map(x => { return x * 2 });
ints.map((x) => { return x * 2 });
ints.map(function(x){return x * 2 });
ints.map(function doubler(x){ return x * 2 });
Don't even get me started on Scala.
V, being revolutionary in its one-way-only idea (lots of languages CLAIM to have "one way" to do something, but they have 3 or 4), should perhaps only have ONE lambda syntax: the original fn syntax without a name. No implicit returns, no syntactic shorthands. This would be different, but WAY more explicit. What do you think?
@N8python
I think it's a very good option, if you mean only having ints.map(fn (x int) { return x * 2 })
More typing, but having only one way fits really well with V's philosophy.
I like : ints.map(fn (x int) { return x * 2 }) This is clear and clean...
Can you declare "local" functions like:
fn main() {
a:=3
c:= 4
fn check(x int) bool {
// some checks here
return true
}
check(a)
check(b)
Of course inline code ;-)