Skip to content

Instantly share code, notes, and snippets.

@elizarov
Last active March 9, 2021 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elizarov/b0496d4bb333172aa37b093c1f108fce to your computer and use it in GitHub Desktop.
Save elizarov/b0496d4bb333172aa37b093c1f108fce to your computer and use it in GitHub Desktop.
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