digitalmars.D.learn - What does the [] operator do here?
- Net (19/19) Apr 01 2020 from the below code, the expression "case [c]":
- Steven Schveighoffer (5/27) Apr 01 2020 heh, it's an array of one character, i.e. an immutable char[] of length
- Adam D. Ruppe (3/4) Apr 01 2020 That's just an array literal, so the same as like
- Net (2/2) Apr 01 2020 oh, i see. That was a dump question. I don't code in D has been a
- WebFreak001 (10/29) Apr 02 2020 the `static foreach (c; "+-*/")` operates on the characters, so c
from the below code, the expression "case [c]":
void main()
{
import std.stdio, std.string, std.algorithm, std.conv;
// Reduce the RPN expression using a stack
readln.split.fold!((stack, op)
{
switch (op)
{
// Generate operator switch cases statically
static foreach (c; "+-*/")
case [c]:
return stack[0 .. $ - 2] ~
mixin("stack[$ - 2] " ~ c ~
" stack[$ - 1]");
default: return stack ~ op.to!real;
}
})((real[]).init).writeln;
}
Apr 01 2020
On 4/1/20 3:35 PM, Net wrote:
from the below code, the expression "case [c]":
void main()
{
import std.stdio, std.string, std.algorithm, std.conv;
// Reduce the RPN expression using a stack
readln.split.fold!((stack, op)
{
switch (op)
{
// Generate operator switch cases statically
static foreach (c; "+-*/")
case [c]:
return stack[0 .. $ - 2] ~
mixin("stack[$ - 2] " ~ c ~
" stack[$ - 1]");
default: return stack ~ op.to!real;
}
})((real[]).init).writeln;
}
heh, it's an array of one character, i.e. an immutable char[] of length
1 (or a string).
Kind of clever actually.
-Steve
Apr 01 2020
On Wednesday, 1 April 2020 at 19:35:30 UTC, Net wrote:from the below code, the expression "case [c]":That's just an array literal, so the same as like "" ~ c
Apr 01 2020
oh, i see. That was a dump question. I don't code in D has been a while and totally forget to create a new array was as simple as []
Apr 01 2020
On Wednesday, 1 April 2020 at 19:35:30 UTC, Net wrote:
from the below code, the expression "case [c]":
void main()
{
import std.stdio, std.string, std.algorithm, std.conv;
// Reduce the RPN expression using a stack
readln.split.fold!((stack, op)
{
switch (op)
{
// Generate operator switch cases statically
static foreach (c; "+-*/")
case [c]:
return stack[0 .. $ - 2] ~
mixin("stack[$ - 2] " ~ c ~
" stack[$ - 1]");
default: return stack ~ op.to!real;
}
})((real[]).init).writeln;
}
the `static foreach (c; "+-*/")` operates on the characters, so c
will be a char.
You use c in the case for the `switch (op)` where op is some char
array (string), so if you want to check it in the switch, you
will have to make c an array.
Here the example uses [c] but you could also `static foreach (c;
["+", "-", "*", "/"])` but I think [c] is a more elegant solution
because it's done at compile time anyway. (case values are
evaluated at compile time like if you would write enum x = [c];)
Apr 02 2020









Steven Schveighoffer <schveiguy gmail.com> 