Skip to content

Instantly share code, notes, and snippets.

@422404
Created January 9, 2020 22:18
Show Gist options
  • Save 422404/1530f2ccb27c2b063de494d9b7968438 to your computer and use it in GitHub Desktop.
Save 422404/1530f2ccb27c2b063de494d9b7968438 to your computer and use it in GitHub Desktop.
import kotlin.ranges.*
// While
fun whileTrueRepeat(target: () -> Boolean, body: () -> Unit): Unit {
if (target()) {
body()
whileTrueRepeat(target, body)
}
}
infix fun (() -> Boolean).whileTrue(body: () -> Unit): Unit {
whileTrueRepeat(this, body)
}
// If/else
interface ITestValue {
infix fun ifTrue(body: () -> Unit): ITestValue
infix fun ifFalse(body: () -> Unit): ITestValue
}
object TrueValue: ITestValue {
override infix fun ifTrue(body: () -> Unit): ITestValue {
body()
return this
}
override infix fun ifFalse(body: () -> Unit): ITestValue = this
}
object FalseValue: ITestValue {
override infix fun ifTrue(body: () -> Unit): ITestValue = this
override infix fun ifFalse(body: () -> Unit): ITestValue {
body()
return this
}
}
infix fun Boolean.ifTrue(body: () -> Unit): ITestValue {
if (this) {
body()
return TrueValue
}
return FalseValue
}
infix fun Boolean.ifFalse(body: () -> Unit): ITestValue {
if (!this) {
body()
return FalseValue
}
return TrueValue
}
// For
infix fun IntProgression.loop(body: (value: Int) -> Unit): Unit {
for (v in this) {
body(v)
}
}
infix fun LongProgression.loop(body: (value: Long) -> Unit): Unit {
for (v in this) {
body(v)
}
}
infix fun CharProgression.loop(body: (value: Char) -> Unit): Unit {
for (v in this) {
body(v)
}
}
// Repeat
infix fun Int.timesRepeat(body: () -> Unit): Unit {
for (i in 0 until this) {
body()
}
}
infix fun Long.timesRepeat(body: () -> Unit): Unit {
for (i in 0 until this) {
body()
}
}
// tests
fun main() {
var i = 0
{ i < 10 } whileTrue {
i++
println(i)
}
(1 < 10) ifTrue {
println("1 < 10")
} ifFalse {
println("1 >= 10")
}
(1 < 0) ifTrue {
println("1 < 0")
} ifFalse {
println("1 >= 0")
}
11..20 loop { v ->
println(v)
}
3 timesRepeat {
println("hello!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment