feat: Cut

This commit is contained in:
Tibo De Peuter 2025-04-15 15:37:05 +02:00
parent 6469dd6ced
commit 229a8bbc3c
Signed by: tdpeuter
GPG key ID: 38297DE43F75FFE2
7 changed files with 294 additions and 81 deletions

View file

@ -4,6 +4,7 @@ import prolog.Answers
import prolog.Substitutions
import prolog.ast.terms.Functor
import prolog.ast.terms.Goal
import prolog.exceptions.AppliedCut
/**
* Collection of [Clause]s with the same [Functor].
@ -53,6 +54,23 @@ class Predicate : Resolvent {
require(goal.functor == functor) { "Goal functor does not match predicate functor" }
// Try to unify the goal with the clause
// If the unification is successful, yield the substitutions
clauses.forEach { yieldAll(it.solve(goal, subs)) }
clauses.forEach { clause ->
clause.solve(goal, subs).forEach { clauseResult ->
clauseResult.fold(
onSuccess = {
yield(Result.success(it))
},
onFailure = {
if (it is AppliedCut) {
// If it's a cut, yield the result with the left substitutions
yield(Result.failure(AppliedCut(it.subs)))
return@sequence
} else {
yield(Result.failure(it))
}
}
)
}
}
}
}