Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's a bit unclear to me what you want to achieve with your predicate - should it print one student at a time and abort if the user accepts, or should it simply print out all sad students in the list? These would be two slightly different predicates.</p> <p>As to why you're getting duplicates, I guess something in your <code>sad</code> predicate leads to backtracking, meaning it can be evaluated multiple times - use the <code>trace</code> functionality of the prolog interpreter to find out where the backtracking happens. While the best thing to do would be fixing the <code>sad</code> predicate to not backtrack, a workaround would be using a cut after the <code>sad</code> which prevents the backtracking:</p> <pre><code>calculate_sad_moods([]):-!. calculate_sad_moods([X2|Rest2]) :- (sad(X2), !, write(`One of our sad students is: `), write(X2), nl, calculate_sad_moods(Rest2)); calculate_sad_moods(Rest2). </code></pre> <p>The cut means that we need to recurse into <code>calculate_sad_moods</code> after writing the output as we can't reach the <code>or</code> part of the clause anymore (it's been cut away too).</p> <p>If you require the behaviour that the predicate evaluates to true after the first sad student found you could achieve this by using another <code>;</code> before the backtracking in the sadness case:</p> <pre><code>calculate_sad_moods([X2|Rest2]) :- (sad(X2), !, write(`One of our sad students is: `), write(X2), (nl; calculate_sad_moods(Rest2))); %only recurse if user says 'no' calculate_sad_moods(Rest2). </code></pre> <p>As a final note, the predicate name is very misleading as you don't actually calculate anything; maybe <code>print_sad_students</code> would be a more fitting name.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload