@
iseki 新人,没怎么用过 V2EX ,不清楚怎么 po 代码,这里先放个 github 链接:
https://github.com/RiniceSiberia/Co2Dice/tree/master/src/main/java/org/co2dice/mirai/ast以下是文字版代码
interface AstNode <
O
//输出
> {
val name : String
fun operation(param : Map<String,Any>):O
//这个节点的运算方式,计算这个节点的运算结果
fun vacancy() : Boolean
//用来检查能否被插入一个新节点
abstract fun getChild() : List<AstNode<*>>
//获取所有子节点
fun dfs(find : () -> Boolean) : AstNode<*>? {
if (find()) {
return this
}
for (child in getChild()) {
val result = child.dfs(find)
if (result != null) {
return result
}
}
return null
}
}
abstract class LeafNode<O,V>() : AstNode<O> {
abstract var value : V
override fun vacancy(): Boolean {
return false
}
override fun getChild(): List<AstNode<*>> {
return emptyList()
}
}
abstract class BranchNode<T>() : AstNode<T> {
}
abstract class SingleChildNode<I,O> : BranchNode<O>() {
abstract var child : AstNode<I>
override fun vacancy(): Boolean {
return child !is PlaceholderNode
}
override fun getChild(): List<AstNode<I>> {
return listOf(child)
}
}
abstract class PairChildNode<LI,RI,O> : BranchNode<O>() {
abstract var left : AstNode<LI>
//左节点
abstract var right : AstNode<RI>
//右节点
override fun vacancy(): Boolean {
return (left is PlaceholderNode) || (right is PlaceholderNode)
}
override fun getChild(): List<AstNode<*>> {
return listOfNotNull(left,right)
}
abstract class ListChildNode<I,T>(
var childs: MutableList<AstNode<I>> = mutableListOf()
) : BranchNode<List<T>>() {
override fun getChild(): List<AstNode<I>> {
return childs
}
override fun vacancy(): Boolean {
return true
}
}
abstract class EqualsNode<T>(
override var left : AstNode<T>,
override var right : AstNode<T>,
) : PairChildNode<T, T, Boolean>() {
override fun operation(param : Map<String,Any>) : Boolean{
return left.operation(param) == right.operation(param)
}
override fun toString(): String {
return "=="
}
}
class NumberEqualsNode(
left : AstNode<Int> = NumberPlaceholderNode(),
right : AstNode<Int> = NumberPlaceholderNode(),
) : EqualsNode<Int>(left,right) {
override val name: String =
Symbols.NUMBER_EQUALS.name}