CLOVIS
04/07/2023, 9:13 AMfun makeUnique(name: String): String {
var candidate = name
var counter = 1
while (alreadyExists(candidate)) {
candidate += "-$counter"
counter++
}
return candidate
}
• Looks like what you'd write in Java
• More similar to what you'd see in algorithm books
fun makeUnique(name: String): String = sequence {
yield(name)
for (i in 1..Int.MAX_VALUE) {
yield("$name-$it")
}
error("Could not find a unique name")
}.first { !alreadyExists(it) }
• The condition at the end is the result you're expecting (unlike in the first version which tests the opposite of what it wants)
• It's easier to test: the sequence generator could be extracted to another method, allowing to write a unit test of the exact candidates attempted
• It encourages to developer to notice the potential overflow / it has a nice place to put the guardrail
• No mutability (easier to debug? though sequences are not great to debug at the moment)ephemient
04/07/2023, 9:17 AM$name-1-2
CLOVIS
04/07/2023, 9:18 AMCLOVIS
04/07/2023, 9:18 AMephemient
04/07/2023, 9:20 AMsuspend
functions inside sequence operatorsCLOVIS
04/07/2023, 9:21 AMsuspend
I could just replace sequence {}
by flow {}
and it would behave the same, right?ephemient
04/07/2023, 9:23 AMephemient
04/07/2023, 9:24 AMCLOVIS
04/07/2023, 9:25 AMephemient
04/07/2023, 9:26 AMCLOVIS
04/07/2023, 9:26 AMCLOVIS
04/07/2023, 9:27 AMAdam S
04/07/2023, 10:05 AMfun namesSequence(name: String): Sequence<String> =
sequence {
yield(name)
repeat(Int.MAX_VALUE) { i ->
yield("$name-$i")
}
}
fun uniqueName(name: String): String =
namesSequence(name)
.firstOrNull { !alreadyExists(it) }
?: error("Could not find a unique name")
CLOVIS
04/07/2023, 10:06 AMMagdalena Tsolaki
04/07/2023, 10:07 AMephemient
04/07/2023, 10:11 AMfun names(name: String) = sequenceOf(name) + generateSequence(1) { it + 1 }.map { "$name-$it" }
ephemient
04/07/2023, 10:16 AMephemient
04/07/2023, 10:19 AMWout Werkman
04/10/2023, 5:57 PMsequence {
file.inputStream().use { /* yields here */ }
}
Now if you don't fully exhaust this sequence, the finally
block will not be executed.
(Not too relatable maybe, but this should be considered when you want to use generators)CLOVIS
04/10/2023, 6:46 PM