Range to Nullable conversion
Ali Çehreli
acehreli at yahoo.com
Fri Jun 10 17:37:13 UTC 2022
On 6/10/22 10:22, Antonio wrote:
> Is there any alternative to ***range front*** that returns a Nullable
> (i.e. **frontAsMonad** or **frontAsNullable**)?
import std;
// Spelling? :)
auto nullablelize(R)(R range) {
alias E = Nullable!(ElementType!R);
struct Nullablelize {
enum empty = false;
auto front() {
if (range.empty) {
return E();
} else {
return E(range.front);
}
}
void popFront() {
if (!range.empty) {
range.popFront();
}
}
// Other range algorithms like save(), etc. here
}
return Nullablelize();
}
void main() {
// Wow! We can take 10 elements without error. :)
writeln(iota(5)
.filter!(i => i % 2)
.nullablelize
.take(10));
}
Ali
More information about the Digitalmars-d-learn
mailing list