Added loose operators

This commit is contained in:
Tibo De Peuter 2025-05-09 16:50:20 +02:00
parent 717e5e0954
commit a9bb6e0338
Signed by: tdpeuter
GPG key ID: 38297DE43F75FFE2
6 changed files with 95 additions and 47 deletions

View file

@ -1,5 +1,6 @@
package prolog.builtins
import com.sun.tools.javac.resources.CompilerProperties.Fragments.Anonymous
import prolog.Answers
import prolog.Substitutions
import prolog.ast.Database.Program
@ -16,6 +17,8 @@ import prolog.ast.lists.List.Cons
*
* If Term is a [Variable] it is unified with a new term whose arguments are all different variables.
* If Term is [atomic], Arity will be unified with the integer 0, and Name will be unified with Term.
*
* Source: [SWI-Prolog Predicate functor/3](https://www.swi-prolog.org/pldoc/doc_for?object=functor/3)
*/
class FunctorOp(private val term: Term, private val functorName: Term, private val functorArity: Term) :
Structure(Atom("functor"), listOf(term, functorName, functorArity)) {
@ -154,30 +157,6 @@ class ClauseOp(private val head: Head, private val body: Body) :
)
}
class AtomicOp(private val term: Term) : Operator(Atom("atomic"), null, term) {
override fun satisfy(subs: Substitutions): Answers {
return if (atomic(term, subs)) {
sequenceOf(Result.success(emptyMap()))
} else {
emptySequence()
}
}
override fun applySubstitution(subs: Substitutions): AtomicOp = AtomicOp(term.applySubstitution(subs))
}
class CompoundOp(private val term: Term) : Operator(Atom("compound"), null, term) {
override fun satisfy(subs: Substitutions): Answers {
return if (compound(term, subs)) {
sequenceOf(Result.success(emptyMap()))
} else {
emptySequence()
}
}
override fun applySubstitution(subs: Substitutions): CompoundOp = CompoundOp(term.applySubstitution(subs))
}
open class Univ(private val term: Term, private val list: Term) : Operator(Atom("=.."), term, list) {
override fun satisfy(subs: Substitutions): Answers {
return when {
@ -246,3 +225,23 @@ open class Univ(private val term: Term, private val list: Term) : Operator(Atom(
list.applySubstitution(subs)
)
}
class NumberVars(private val term: Term, private val start: Integer, private val end: Term) :
Structure(Atom("numbervars"), listOf(term, start, end)) {
private var yieldEnd: Boolean = true
constructor(term: Term) : this(term, Integer(0), AnonymousVariable.create()) {
yieldEnd = false
}
override fun satisfy(subs: Substitutions): Answers = sequence {
val (newEnd, newSubs) = numbervars(term, start.value, subs)
unifyLazy(end, Integer(newEnd), subs).forEach { endResult ->
endResult.map { endSubs ->
val result = if (yieldEnd) (newSubs + endSubs) else newSubs
yield(Result.success(result))
}
}
}
}