https://kotlinlang.org logo
Title
i

igor.wojda

11/08/2018, 5:47 PM
Can somebody give me good example of using
CharSequence.reduce
function?
d

dalexander

11/08/2018, 6:15 PM
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

hudsonb

11/08/2018, 6:20 PM
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

dalexander

11/08/2018, 6:21 PM
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

r4zzz4k

11/08/2018, 7:16 PM
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

hudsonb

11/08/2018, 7:24 PM
Right, seems like
reduce
may just be included for consistency as Derek suggested.
r

r4zzz4k

11/08/2018, 7:24 PM
Most probably so, yeah.
i

igor.wojda

11/08/2018, 9:48 PM
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

karelpeeters

11/08/2018, 10:18 PM
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

igor.wojda

11/08/2018, 11:30 PM
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

karelpeeters

11/08/2018, 11:32 PM
List<Char>.reduce
is exactly the same as
CharSequence.reduce
, right?