Allow "*" on lists and strings to repeat them.
This is not implemented on Sequence because, at least for lists and strings, I think users expect an eager result. Multiplying a string should give you back a string, not a lazy sequence of repeated characters. This also mirrors "+" on strings and lists, which is eager. I like the idea of having a general guideline that operators are eager. Repetition is useful for arbitrary sequences, but for that maybe we should add a "repeat()" method.
This commit is contained in:
@@ -131,6 +131,18 @@ class WhereSequence is Sequence {
|
||||
class String is Sequence {
|
||||
bytes { StringByteSequence.new(this) }
|
||||
codePoints { StringCodePointSequence.new(this) }
|
||||
|
||||
*(count) {
|
||||
if (!(count is Num) || !count.isInteger || count < 0) {
|
||||
Fiber.abort("Count must be a non-negative integer.")
|
||||
}
|
||||
|
||||
var result = ""
|
||||
for (i in 0...count) {
|
||||
result = result + this
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
class StringByteSequence is Sequence {
|
||||
@@ -174,6 +186,18 @@ class List is Sequence {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
*(count) {
|
||||
if (!(count is Num) || !count.isInteger || count < 0) {
|
||||
Fiber.abort("Count must be a non-negative integer.")
|
||||
}
|
||||
|
||||
var result = []
|
||||
for (i in 0...count) {
|
||||
result.addAll(this)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
class Map {
|
||||
|
||||
@@ -133,6 +133,18 @@ static const char* coreModuleSource =
|
||||
"class String is Sequence {\n"
|
||||
" bytes { StringByteSequence.new(this) }\n"
|
||||
" codePoints { StringCodePointSequence.new(this) }\n"
|
||||
"\n"
|
||||
" *(count) {\n"
|
||||
" if (!(count is Num) || !count.isInteger || count < 0) {\n"
|
||||
" Fiber.abort(\"Count must be a non-negative integer.\")\n"
|
||||
" }\n"
|
||||
"\n"
|
||||
" var result = \"\"\n"
|
||||
" for (i in 0...count) {\n"
|
||||
" result = result + this\n"
|
||||
" }\n"
|
||||
" return result\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"\n"
|
||||
"class StringByteSequence is Sequence {\n"
|
||||
@@ -176,6 +188,18 @@ static const char* coreModuleSource =
|
||||
" }\n"
|
||||
" return result\n"
|
||||
" }\n"
|
||||
"\n"
|
||||
" *(count) {\n"
|
||||
" if (!(count is Num) || !count.isInteger || count < 0) {\n"
|
||||
" Fiber.abort(\"Count must be a non-negative integer.\")\n"
|
||||
" }\n"
|
||||
"\n"
|
||||
" var result = []\n"
|
||||
" for (i in 0...count) {\n"
|
||||
" result.addAll(this)\n"
|
||||
" }\n"
|
||||
" return result\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
"\n"
|
||||
"class Map {\n"
|
||||
|
||||
Reference in New Issue
Block a user