/tmp/duangsuse.sock
23 subscribers
303 photos
3 videos
92 files
337 links
从 duangsuse::Echo (@dsuse) 跟进出来的分支,将在作者恢复原帐号访问的时候合并删除。
Download Telegram
Calc.kt
4.3 KB
终于又写了点代码,打算写个计算器来着
sealed class Trie<K, V> {
data class Path<K, V>(val routes: MutableMap<K, Trie<K, V>>): Trie<K, V>() {
constructor(): this(mutableMapOf())
override fun toString() = "Path${routes}"
operator fun get(key: List<K>): Trie<K, V> {
var point = this
for ((i, k) in key.withIndex()) point = try {
point.routes[k]?.asPath() ?: throw ClassCastException() }
catch (_: ClassCastException) {
if (i == key.lastIndex) {
point.routes[k]?.let { return it }
}
error(key, k)
}
return point
}
fun getOrCreatePath(key: Iterable<K>): Path<K, V> {
var point = this
for (k in key) point = try { point.routes.getOrPut(k, ::Path).asPath() }
catch (_: ClassCastException) { error(key, k) }
return point
}
operator fun set(key: List<K>, value: V) {
val containerKey = key.subList(0, key.lastIndex)
val container = getOrCreatePath(containerKey)
val k1 = key[key.lastIndex]
container.routes[k1] = Term(value)
}
private fun error(key: Iterable<K>, k: K): Nothing {
val msg = "${key.joinToString("/")} $k"
throw NoSuchElementException(msg)
}
}
data class Term<K, V>(var value: V): Trie<K, V>()
fun asPath(): Path<K, V> = this as Path
fun asTerm(): Term<K, V> = this as Term
}
#Kotiln
data class Trie<K, V>(var value: V?) {
constructor(): this(null)
val routes: MutableMap<K, Trie<K, V>> by lazy(::mutableMapOf)
override fun toString() =
if (value == null) "Path${routes}"
else "Bin[$value]${routes}"
fun getOrCreatePath(key: Iterable<K>): Trie<K, V> {
var point = this
for (k in key) point = point.routes.getOrPut(k, ::Trie)
return point
}
operator fun get(key: Iterable<K>): Trie<K, V> {
var point = this
for (k in key) point = point.routes[k] ?: errorNoPath(key, k)
return point
}
operator fun set(key: Iterable<K>, value: V) {
getOrCreatePath(key).value = value
}
private fun errorNoPath(key: Iterable<K>, k: K): Nothing {
val msg = "${key.joinToString("/")} @$k"
throw NoSuchElementException(msg)
}
}
其实这个 trie 本来是比较简单的,不过我的建模有问题,就写复杂了……
#Kotlin 想要给一个 List<MutableList<T>> 做 Lazy 真麻烦,by 还不能放在 primary constructor 里,delegate by lazy 也不可以。
Calc.kt
7.1 KB
#Kotlin #code 这是 jison 里部分代码的第二次重写,以后有机会我用 jison org.parserkt 里原有的测试来验证一下它们
fun <T: Any> Feed<T>.takeWhile(predicate: Predicate<T>): Sequence<T> = generateSequence {
peek.takeIf(predicate)?.let { runCatching(::consume).getOrNull() }
}

fun <T> Feed<T>.takeWhile(predicate: Predicate<T>): Sequence<T> = sequence {
while (true)
if (predicate(peek)) yield(runCatching(::consume).getOrNull() ?: break)
else break
}


#Kotlin sequences 好棒棒呀,一个 or 的逻辑从三行简化到了一行。
Calc.kt
12.5 KB
#Kotlin #code 又写了许多,已经开始觉得没必要了
Calc.kt
15.3 KB
#Kotlin #code 终于完成了字典树
Calc.kt
15.4 KB
#Kotlin #code 简化了一下字典树
其实对缩进布局的解析根本不需要抛 exception,子布局返回的数据里放终止嵌套层次就可以做到级联收尾了。