Reputation: 9532
I am trying to get on Kotlin so I am following this tutorial of their own.
So they're trying to create a sequence given a string, such as this:
"a vect" -> [
a vect :
a vec : t
a ve : ct
...
]
And the way to do it is, according to the video, the following:
val seq = sequenceOf(canonicalisedInput.lastIndex + 1 downTo 0).map {
canonicalisedInput.substring(0, it) to canonicalisedInput.substring(it)
}
And I get what I does (well, the idea of it). The problem is that substring
expects two Int
s, while it
(which I assume is an implicit iterator of some sorts that comes from the downTo
progression) is an IntProgression
. Same for the second substring
call.
What am I missing?
Upvotes: 3
Views: 238
Reputation: 148129
The code you posted contains a mistake: sequenceOf(...)
with single argument passed returns a sequence with that one item, that is, Sequence<IntProgression>
. To get a sequence of indices (Sequence<Int>
), use asSequence()
function instead:
(canonicalisedInput.lastIndex + 1 downTo 0).asSequence().map { ... }
The substring(...)
function called second is the overload that returns the substring starting from the index passed as the argument.
And it
is the implicit name for the innermost lambda single parameter, in your case it is the parameter of map
, that is, the sequence item to be mapped by the lambda.
So, the expression inside lambda is a pair (created by to
infix function) of two substring, one from the beginning of the original string to the index in the sequence, the other one -- from that index to the end of the string.
So the code should definitely work with indices sequence, that's why the mistake is quite clear.
Upvotes: 4
Reputation: 23154
sequenceOf(canonicalisedInput.lastIndex + 1 downTo 0)
—
this expression creates a sequence which consists of a single IntProgression
item.
If you want to convert an IntProgression
to a Sequence<Int>
, use asSequence
extension function:
(canonicalisedInput.length downTo 0).asSequence()
Upvotes: 3