Created
August 4, 2019 14:25
-
-
Save happy-bracket/2eca7cdf0aed4a4b0f81638961d7b7ad to your computer and use it in GitHub Desktop.
This file contains 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
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 | |
} | |
} | |
This file contains 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
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