On Friday, 13 August 2021 at 23:21:42 UTC, Ali Çehreli wrote:
On 8/13/21 4:08 PM, jfondren wrote:
On Friday, 13 August 2021 at 22:09:59 UTC, Marcone wrote:
Isn't there some unario operator template that I can use with
lambda to handle a string literal?
So, something other than an exact "lit"[0..this.xx(..)] syntax
is fine?
What didn't you like about `"Hello
World!".findSplit("o")[0].writeln;` then?
What is a real example of something you want to do?
And I started writing the following but stopped because the
semantics are not clear. I first called it 'between' but then
should the 'o' that was searched be a part of the output?
Should "from 'o' to 'o'" produce an empty string, should it
include a single 'o' or should it go all the way to the next
'o'?
What about the last line which says "from 'd' to 'a'"? Is that
an entirely empty range or just 'd' or 'd' till the end?
I don't think the programming language can decide one way or
the other.
import std.algorithm;
import std.range;
import std.stdio;
auto inclusive(R, E)(R range, E fromNeedle, E toNeedle) {
auto found = range.find(fromNeedle);
return chain(found.front.only,
found.drop(1).findSplitAfter(only(toNeedle))[0]);
}
void main() {
const s = "Hello World!";
auto r = s.inclusive('o', 'o');
writeln(r);
writeln("abcdef".inclusive('d', 'a'));
}
Ali
import std;
class None {}
// Function slice()
auto slice(T1, T2, T3 = None)(T1 conteudo, T2 inicio, T3 fim =
T3.init) {
int start, end, startlen;
static if (is(T2 == int)) {inicio = inicio < 0 ? conteudo.length
+ inicio : inicio;}
static if (is(T3 == int)) {fim = fim <= 0 ? conteudo.length +
fim : fim;}
static if (is(T2 == int)) {start = inicio;} else static if
(is(T2 == string)){start = conteudo.countUntil(inicio);}
static if (is(T2 == string)) {static if (is(T1 ==
string)){startlen = start + inicio.length + 1;} else {startlen =
start + 1;}}
static if (is(T3 == int)) {end = fim;} else static if (is(T3 ==
string)){end = startlen + conteudo[startlen..$].countUntil(fim);}
static if (is(T3 == None)) {return conteudo[start];} else
{return conteudo[start..end];}
}
void main(){
writeln("Hello World!".slice(1, 8)); // ello Wo
writeln("Hello World!".slice("e", "r")); // ello Wo
writeln("Hello World!".slice(1, "r")); // ello Wo
writeln("Hello World!".slice("e", 8)); // ello Wo
writeln("Hello World!".slice(6, -1)); // World (Same as $-1)
writeln("Hello World!".slice(-12, -7)); // Hello (Same as $-12,
$-7)
writeln("Hello World!".slice("W", -1)); // World (Same as "W",
$-1)
writeln("Hello World!".slice(-12, " ")); // Hello (Same as $-12,
" ")
}
Like this function, but inside []. So I can use functions to get
index for slice.