Reputation: 41
Let's say that I have the following list in my prolog:
L=[10,11,2,3,5]
Is there a way that we can check all the members of a list L
to make sure that each member is less than 5
?
Upvotes: 1
Views: 348
Reputation: 71
Here goes another solution without using any built-in function:
all_less_five([]).
all_less_five([X|L]):-
X < 5,
all_less_five(L).
This solution uses the typical recursion over lists. The predicate stands true for the empty list, and then we only call the recursion over the tail if the head is less than five.
Here are some questions over the predicate:
?- all_less_five([10,11,2]).
false.
?- all_less_five([2,3,6,5]).
false.
?- all_less_five([1,2,3,4]).
true.
Now it should be easy to implement it to any given X. Try it!
Upvotes: 0
Reputation: 477881
We can make use of maplist/2
here. This is a predicate that:
maplist(:Goal, ?List)
True
ifGoal
can successfully be applied on all elements ofList
. Arguments are reordered to gain performance as well as to make the predicate deterministic under normal circumstances.
So we can here check the elements with:
all_less_five(L) :-
maplist(>(5), L).
Here for every element x ∈ L, it will thus call >(5, x)
, or in inline form 5 > x
. So if all these elements are less than five, the the all_less_five/1
predicate will succeed.
For example:
?- all_less_five([10,11,2,3,5]).
false.
?- all_less_five([2,3,5]).
false.
?- all_less_five([2,3]).
true.
Upvotes: 1