Last active
July 4, 2023 20:40
-
-
Save KosmX/a48e4b9ff5217343c3c780b662f8dc12 to your computer and use it in GitHub Desktop.
A computer can never be help accountable therefore a computer must never make a *management* decision [meme]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.jetbrains.annotations.ApiStatus.Internal | |
import kotlin.contracts.ExperimentalContracts | |
import kotlin.contracts.InvocationKind | |
import kotlin.contracts.contract | |
// helper function | |
fun userCondition(msg: String): Boolean { | |
while (true) { | |
println("$msg [Y/N]") | |
val r = readln().firstOrNull()?.uppercaseChar() | |
if (r == 'Y') { | |
return true | |
} else if (r == 'N') { | |
return false | |
} | |
} | |
} | |
inline fun decide(msg: String, block: () -> Unit) { | |
contract { | |
callsInPlace(block, InvocationKind.AT_MOST_ONCE) | |
} | |
if (userCondition(msg)) block() | |
} | |
fun decide(msg: String): PreDecideResult = PreDecideResult(userCondition(msg)) | |
inline infix fun <T> PreDecideResult.between(block: () -> T): BlockResult<T>? { | |
contract { | |
callsInPlace(block, InvocationKind.AT_MOST_ONCE) | |
} | |
return if (condition) BlockResult(block()) else null | |
} | |
inline infix fun <T> BlockResult<T>?.and(block: () -> T): T { | |
contract { | |
callsInPlace(block, InvocationKind.AT_MOST_ONCE) | |
} | |
return if (this == null) { | |
block() | |
} else { | |
t | |
} | |
} | |
inline fun <T> choose(msg: String, block: ChooseInternalBlock<T>.() -> Unit): T? { | |
val collector = ChooseInternalBlock<T>() | |
block(collector) | |
while (true) { | |
println("$msg, Choose one branch from ${collector.choices}") | |
val r = readln() | |
if (r in collector.choices) { | |
ChooseInternalBlock<T>(r).let { | |
block(it) | |
return@choose it.r | |
} | |
} | |
println("$r is an invalid choice.") | |
} | |
} | |
@Internal | |
class PreDecideResult(val condition: Boolean) | |
@Internal | |
class BlockResult<T>(val t: T) | |
class ChooseInternalBlock<T>(val choice: String? = null, val choices: MutableList<String> = mutableListOf(), var r: T? = null) { | |
inline infix fun String.to(block: () -> T) { | |
if (choice == null) choices += this | |
else if (choice == this) r = block() | |
} | |
inline fun default(block: () -> T) { | |
if (choice == null) choices += "default" | |
else if (choice == "default") r = block() | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And a perfect example of abusing it: