Skip to content

Instantly share code, notes, and snippets.

@happy-bracket
Created August 4, 2019 14:25
Show Gist options
  • Save happy-bracket/2eca7cdf0aed4a4b0f81638961d7b7ad to your computer and use it in GitHub Desktop.
Save happy-bracket/2eca7cdf0aed4a4b0f81638961d7b7ad to your computer and use it in GitHub Desktop.
class BetterWhen<T, R>(val appl: T) {
var result: R? = null
fun cond(p: (T) -> Boolean, res: () -> R) {
if (p(appl)) {
result = res()
throw Interrupt()
}
}
class Interrupt : Exception()
}
fun <T> betterWhen(rec: T, block: BetterWhen.() -> Unit): R? {
val ctx = BetterWhen<T, R>(rec)
return try {
ctx.block()
ctx.result
} catch (e: BetterWhen.Interrupt) {
ctx.result
}
}
fun Int.eq(other: Int): Boolean {
return this == other
}
fun <A, B, R> ((A, B) -> C).partial(): (A) -> (B) -> C =
{ a ->
{ b ->
this(a, b)
}
}
fun sample() {
val int = 3
val res =
betterWhen(int) {
cond(::eq.partial()(3)) { "success" }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment