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 = Optional.empty() fun alias(): Optional { return alias } fun bind(term: Term): Optional { if (alias.isEmpty) { alias = Optional.of(term) } return alias } fun unbind() { alias = Optional.empty() } override fun evaluate(subs: Substituted): Pair { // 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 } } }