Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KisaragiEffective/a8cd2f2cf96cf00367b01ef8d3e5c6b7 to your computer and use it in GitHub Desktop.
Save KisaragiEffective/a8cd2f2cf96cf00367b01ef8d3e5c6b7 to your computer and use it in GitHub Desktop.
HList.size()の実装が悪い?
sealed class HList {
class Body<out A, out B : HList>(val head: A, val rest: B) : HList() {
}
object Tail : HList()
companion object {
fun <E1> of(e1: E1) = Body(e1, Tail)
fun <E1, E2> of(e1: E1, e2: E2) = Body(e1, Body(e2, Tail))
}
}
fun HList.size(): Int {
return size(0)
}
private tailrec fun HList.size(acc: Int = 0): Int {
return when (this) {
is HList.Body<*, *> -> this.size(acc + 1)
HList.Tail -> acc
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment