1
votes

Define a sum_threshold (List, Threshold, Sum) predicate to sum the elements of List that have a value greater than or equal to the Threshold.

sum_threshold([Head | Tail], Threshold, Sum) :-
    Head >= Threshold,
    sum_threshold(Tail, Threshold, Sum2),
    Sum is Sum2 + Head.
sum_threshold([Head | Tail], Threshold, Sum) :- 
    Head < Threshold,
    sum_threshold(Tail, Threshold, Sum).

I have compiled the file on SWI-Prolog, but when I do:

sum_threshold([5,3,10,4,7,1], 5, Sum).

It gives me

False

Why??

1
What's your default case?Enigmativity
And your alternative when Head < Threshold.Enigmativity
@Enigmativity I have edited the first question. Did you thing that the false message is why Head < Threshold?Jack23
I add also the Head < Threshold caseJack23

1 Answers

2
votes

You're missing the default case when the list is empty. You need this:

sum_threshold([],_,0).

I then get:

?- sum_threshold([5,3,10,4,7,1], 5, Sum).
Sum = 22 .