A couple of extensions to `with` that would be worthwhile

jfondren julian.fondren at gmail.com
Thu Oct 14 08:37:40 UTC 2021


On Thursday, 14 October 2021 at 07:12:29 UTC, Tejas wrote:
> Maybe having the syntax as:
> ```d
> with <construct> as <identifier>{
>     //do stuff
> }
> ```
> Would be better?

This is completely novel syntax (for d), when the proposed syntax 
is used all over the place in d. How are you going to explain 
this to Scott Meyers, after his whole speech about "please don't 
make the decisions that require professional explainers like me"? 
https://www.youtube.com/watch?v=KAWA1DuvCnQ

> It could also be useful in `Python` style management for `file` 
> handles

It's not as nice but `with` and a scope both offer this (with a 
strace confirming that the file is closed before the writeln):

```d
void main() {
     import std.stdio : File, writeln, stdout;

     with (File("/etc/passwd")) {
         stdout.write(readln); // std.stdio.write is shadowed by 
File
     }
     writeln("that's enough");
}

void main() {
     import std.stdio : File, writeln, write;

     {
         auto file = File("/etc/passwd");
         // at least there's no extra nesting for multiple files?
         write(file.readln);
     }
     writeln("that's enough");
}
```

> , plus be visually distinct enough from other uses of `with` to 
> not simply be overlooked.

but if we're adding syntax, how about something to make tuple 
deconstruction a little bit nicer? `with` already offers that but 
nobody's noticed in the other thread about what they'd like in d, 
because of how much work it is:

```d
import std.stdio : writeln;
import std.typecons : Tuple;

unittest {
     struct S { int a; float b; }
     with (S(1, 2)) {
         writeln(a);
         writeln(b);
     }
}

auto opaque() {
     struct S { char a; ubyte b; }
     return S('a', 'b');
}

unittest {
     with (Tuple!(char, "x", ubyte, "y")(opaque().tupleof)) {
         writeln(x);
         writeln(cast(char) y);
     }
}
```

the proposed `with():` would get rid of the nesting that's not 
wanted for tuple deconstruction, but naming could still be 
improved. How about borrowing from foreach?

```d
unittest {
     with (char x, ubyte y; opaque): // implicit .tupleof
     writeln(x);
     writeln(cast(char) y);
}
```


More information about the Digitalmars-d mailing list