50 lines
No EOL
1.2 KiB
Kotlin
50 lines
No EOL
1.2 KiB
Kotlin
package prolog.ast.terms
|
|
|
|
import prolog.ast.arithmetic.Expression
|
|
import prolog.logic.Substituted
|
|
import java.util.*
|
|
|
|
data class Variable(val name: String) : Term, Expression {
|
|
private var alias: Optional<Term> = Optional.empty()
|
|
|
|
fun alias(): Optional<Term> {
|
|
return alias
|
|
}
|
|
|
|
fun bind(term: Term): Optional<Term> {
|
|
if (alias.isEmpty) {
|
|
alias = Optional.of(term)
|
|
}
|
|
|
|
return alias
|
|
}
|
|
|
|
fun unbind() {
|
|
alias = Optional.empty()
|
|
}
|
|
|
|
override fun evaluate(subs: Substituted): Pair<Term, Substituted> {
|
|
// If the variable is bound, return the value of the binding
|
|
// If the variable is not bound, return the variable itself
|
|
return if (alias.isPresent) {
|
|
alias.get().evaluate(subs)
|
|
} else {
|
|
Pair(this, emptyMap())
|
|
}
|
|
}
|
|
|
|
override fun compareTo(other: Term): Int {
|
|
return when (other) {
|
|
is Variable -> name.compareTo(other.name)
|
|
// Variables are always less than atoms
|
|
else -> -1
|
|
}
|
|
}
|
|
|
|
override fun toString(): String {
|
|
return when {
|
|
alias.isPresent -> "$name: ${alias.get()}"
|
|
else -> name
|
|
}
|
|
}
|
|
} |