| |
| Posted by Ali Çehreli in reply to rempas | PermalinkReply |
|
Ali Çehreli
Posted in reply to rempas
| On 7/9/21 12:21 AM, rempas wrote:
> while (prompt[i] != '{' && i < len) {
In addition to what others said, you can take advantage of ranges to separate concerns of filtering and iteration. Here are two ways:
import core.stdc.stdio;
import std.algorithm;
// Same as your original
void print(T)(string prompt, T args...) {
prompt
.filter!(c => c != '{')
.each!(c => printf("%c", c));
// If you are not familiar with the shorthand lambda syntax,
// I read c => foo(c) as "given c, produce foo(c)."
//
// Well... 'each' is different because it does not
// produce anything. It its case: "given c, do this."
}
// This one dispatches filtering to another function but
// still uses a 'foreach' loop
void print2(T)(string prompt, T args...) {
foreach (c; prompt.sansCurly) {
printf("%c", c);
}
}
// I used R instead of 'string' in case it will be more useful
auto sansCurly(R)(R range) {
return range.filter!(c => c != '{');
}
void main() {
print("Hello, {world!\n", 10);
print2("Hello, {world!\n", 10);
}
Ali
|