ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
33.69k stars 2.47k forks source link

feature request: arrow function syntax #13542

Closed notramo closed 1 year ago

notramo commented 1 year ago

Zig doesn't have a nice syntax for passing lambda functions as callbacks. Arrow syntax could make it more readable. It

// simply calls the function provided in arguments
callFunction( func: fn (u8, u8) bool ) bool {
  return func(1, 2);
}

test "testing" {
  _ = callFunction( struct {
    fn callback(a: u8, b: u8) bool {
      return a < b;
    }
  }.callback);
}

// arrow syntax
// basically syntax sugar for the above
test "arrow syntax" {
  _ = callFunction(
    fn (a: u8, b: u8) => a < b
  )
}
jedisct1 commented 1 year ago

A better way to use lambdas would indeed be convenient.

However, the arrow syntax is not the panacea.

With the arrow syntax, => can play completely different roles according to the context, and that hurts readability.

Your example => a < b perfectly illustrates that. (b: u8) => a => b would be awful.

Not having to wrap lambdas in a structure may be better. Achieving the same goal, without introducing a new syntax. I think there's already an issue about that.

mlugg commented 1 year ago

Related: #1717

ifreund commented 1 year ago

https://github.com/ziglang/zig/wiki/Language-Proposals

lerno commented 1 year ago

@jedisct1 For what it's worth I recently added lambdas to C3 which was a natural extension of a "short function" syntax I had:

// Regular function in C3
fn int square(int x)
{
    return x * x;
}
fn int square_short(int x) => x * x;

From this syntax, I could derive both a regular lambda syntax and a short variant:

// Full
apply_int(arr, fn int(int x) { return x * x });
// Inference
apply_int(arr, fn (x) { return x * x; });
// Short + inference
applyInt(arr, fn (x) => x * x);

(=> can be replaced by some other unambiguous token)

Returning a lambda would be something like fn () => fn (x) => x * x;

While lambdas can be rejected on other grounds, I don't think syntax is one of them. It should be possible to do something similar to the above fitting nicely with Zig syntax.

rainxh11 commented 8 months ago

arrow function syntax is much better looking, and better to type syntax, i don't know why they went with the Rust horrible |x| syntax and the | key in keyboard is only convenient for QWERTY keyboards

nektro commented 8 months ago

I really love @lerno's syntax but would argue that if Zig were to implement this it should only accept the "Inference" version