Can somebody give me good example of using `CharSe...
# announcements
i
Can somebody give me good example of using
CharSequence.reduce
function?
d
This is not a “good” example in the sense that there might be better ways to do it, but here is an example using fold (I consider reduce a trap since it will crash with an empty list).
val aCount = "the rain in spain falls mainly in the plain".fold(0, {sum, cur -> sum + if(cur == 'a') { 1 } else { 0 }})
h
Seems odd that they require the accumulator to be a
Char
.
reduce
in Swift for example allows you to provide the initial value for the accumulator which is far more flexible/useful. I can't think of a use case for
reduce
, as is, that couldn't be accomplished better using other methods.
d
Yeah, I was going to add that I’m not sure if there’s a reason to have a reduce on Char since the accumulator is a Char other than for consistency between map/reduce-able types.
r
There is also
.fold
, which allows you to use any type for accumulator and pass it's initial value. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/fold.html (Same goes for collections and sequences, by the way)
h
Right, seems like
reduce
may just be included for consistency as Derek suggested.
r
Most probably so, yeah.
i
This confirm my suspicions that
reduce
may be not that useful for Char-sequence/String classes. Thanks guys for the fold tip and thanks@r4zzz4k for info that
fold
have different accumulator type then
reduce
- this is what I needed
k
Tbh I haven't had a use for
reduce
at all yet, lots of
fold
though.
reduce
on charsequences doesn't make less sense than on lists though, unless I'm missing something.
i
It makes more sense on lists because accumulator and current item will have the same type as list type argument, so
String/Charsequence
- accumulator/current is
Char
List<Int>
- accumulator/current is
Int
List<String>
- accumulator/current is
String
So having eg.
List<Int>
you could sum up the items or sum up only odd items. I guess in this case we could use reduce and fold, however with
String/Charsequence
reduce is not an option (because accumulator/current is
Char
) while fold accumulator is
String
and current is
Char
k
List<Char>.reduce
is exactly the same as
CharSequence.reduce
, right?