Danish Ansari
08/16/2021, 7:58 AMIntRange
using onEach
function like this
val range = (1..3).onEach { it + 1}
println(range) // expecting 2..4 but still getting 1..3
So what should I try?thana
08/16/2021, 8:09 AMonEach
is mainly used fore side effects triggered on each element, but doesn't change anything. Use map
in your caseCLOVIS
08/16/2021, 8:14 AM(T) -> Unit
, which means it ignores whatever you give to itDanish Ansari
08/16/2021, 8:16 AMmap
returns List
but I want IntRange
thana
08/16/2021, 8:18 AMDanish Ansari
08/16/2021, 8:19 AMval range = 1..3
val modifiedRange = range.first..range.last
thana
08/16/2021, 8:20 AMDanish Ansari
08/16/2021, 8:21 AMCLOVIS
08/16/2021, 8:23 AMCLOVIS
08/16/2021, 8:24 AMval r = -5..5
val g = r.mapNewRange { abs(it) }
thana
08/16/2021, 8:26 AMthana
08/16/2021, 8:26 AMDanish Ansari
08/16/2021, 8:27 AMIntRange
will never have negative valueDanish Ansari
08/16/2021, 8:27 AMCLOVIS
08/16/2021, 8:29 AMmap
shouldn't change the size of the functor)thana
08/16/2021, 8:30 AMthana
08/16/2021, 8:31 AMephemient
08/16/2021, 8:32 AMval r = 0..Int.MAX_VALUE
val g = r.mapNewRange { it + 1 }
is also broken. that extension only works if the function is monotonically increasingthana
08/16/2021, 8:32 AMCLOVIS
08/16/2021, 8:32 AM// Size: 6
val r = 0..5
// Size: 6 (0, 1, 0, 1, 0, 1)
val l = r.map { it % 2 }
// Size: 2 (0, 1)
val g = r.mapNewRange { it % 2 }
thana
08/16/2021, 8:32 AMephemient
08/16/2021, 8:34 AMval r = 0..5
val l = r.map { it % 4 }
val g = r.mapNewRange { it % 4 }
even if you sort l
back into a range, it still contains more elements than g
CLOVIS
08/16/2021, 8:34 AMIterator
or Sequence
instead of a List
thana
08/16/2021, 8:34 AM+
is brokenDanish Ansari
08/16/2021, 8:35 AMthana
08/16/2021, 8:35 AMephemient
08/16/2021, 8:36 AMr.map { it / 2 }.toSet().size == r.mapNewRange { it / 2 }.size
CLOVIS
08/16/2021, 8:37 AMmap
should never have an impact on the sizeephemient
08/16/2021, 8:39 AM.mapTo(mutableSetOf()) { it / 2 }
can change the size, but yeah I agree this case should definitely not be called "map"ephemient
08/16/2021, 8:39 AMCLOVIS
08/16/2021, 8:42 AMephemient
08/16/2021, 9:11 AM{ -it }
ephemient
08/16/2021, 9:12 AMCLOVIS
08/16/2021, 9:32 AMstep
, but yeah that's very limitingZach Klippenstein (he/him) [MOD]
08/16/2021, 1:49 PMI just wish the standard library returned an
Iterator
or Sequence
instead of a List
It kind of does - List
implements Iterable
so you can get an Iterator
from it - I don’t see how that solves this problem though.Dave K
08/16/2021, 2:34 PMDave K
08/16/2021, 2:36 PMephemient
08/18/2021, 2:53 AM+
is not broken, it's always well-defined. it's just not monotonic across its entire range of inputsthana
08/18/2021, 5:43 AM