Last active
March 9, 2021 10:11
-
-
Save elizarov/b0496d4bb333172aa37b093c1f108fce to your computer and use it in GitHub Desktop.
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
interface Group<T> { | |
val id: T // identity | |
operator fun T.plus(that: T): T // group operation | |
operator fun T.unaryMinus(): T // inverse | |
} | |
inline class Residue(val x: Int) | |
// Group of residues modulo n | |
class Mod(val n: Int): Group<Residue> { | |
override val id: Residue = Residue(0) | |
override fun Residue.plus(that: Residue): Residue = Residue((x + that.x) % n) | |
override fun Residue.unaryMinus(): Residue = Residue((n - x) % n) | |
} | |
// Contextual functions | |
context(Group<T>) | |
fun <T> Collection<T>.sum(): T { | |
var a = id | |
for (x in this) a += x | |
return a | |
} | |
// Contextual operator | |
context(Group<T>) | |
operator fun <T> T.minus(that: T): T = this + (-that) | |
fun main() { | |
with(Mod(11)) { | |
println(Residue(3) - Residue(5)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment