Reversing a string
AndreasDavour
andreas.davour at protonmail.ch
Fri Jan 11 08:05:39 UTC 2019
Hi.
I've just started to learn some D, so maybe this question is
extremely stupid, but please bear with me.
I have been trying to reverse a string, and through some googling
found the std.algorithm.mutation.reverse method. But, when I try
to use it I get some very verbose errors that just makes my eyes
glaze over. What on earth do they mean? How do I reverse a
string, really?
This is my code:
----------------------------
import std.stdio;
import std.algorithm;
void main() {
auto test = "This is my text";
string next_test = reverse(test);
writeln(test);
writeln(next_test);
}
----------------------------
This is my error:
----------------------------
[ante at tiny ~/src/D/tutorial]$ rdmd string4.d
/usr/home/ante/src/dmd2/freebsd/bin64/../../src/phobos/std/algorithm/mutation.d(2513): Error: template `std.algorithm.mutation.reverse` cannot deduce function from argument types `!()(immutable(ubyte)[])`, candidates are:
/usr/home/ante/src/dmd2/freebsd/bin64/../../src/phobos/std/algorithm/mutation.d(2485): `std.algorithm.mutation.reverse(Range)(Range r) if (isBidirectionalRange!Range && (hasSwappableElements!Range || hasAssignableElements!Range && hasLength!Range && isRandomAccessRange!Range || isNarrowString!Range && isAssignable!(ElementType!Range)))`
/usr/home/ante/src/dmd2/freebsd/bin64/../../src/phobos/std/algorithm/mutation.d(2521): Error: template `std.algorithm.mutation.reverse` cannot deduce function from argument types `!()(immutable(ubyte)[])`, candidates are:
/usr/home/ante/src/dmd2/freebsd/bin64/../../src/phobos/std/algorithm/mutation.d(2485): `std.algorithm.mutation.reverse(Range)(Range r) if (isBidirectionalRange!Range && (hasSwappableElements!Range || hasAssignableElements!Range && hasLength!Range && isRandomAccessRange!Range || isNarrowString!Range && isAssignable!(ElementType!Range)))`
string4.d(6): Error: template instance
`std.algorithm.mutation.reverse!string` error instantiating
Failed: ["/usr/home/ante/src/dmd2/freebsd/bin64/dmd", "-v",
"-o-", "string4.d", "-I."]
------------------------------
Can some unpack that for me, please?
I might add that the most intuitive way to reverse a string, I
think, would be to consider it a range and just do "newstring =
oldstring[$ .. 0]" but that gives an error about being out of
bounds, so I guess the compiler expect values to increase from
left to right, and does not want to increment beyond $. Makes
sense, but that syntax would be very neat.
More information about the Digitalmars-d-learn
mailing list