Reputation: 17
Let's say I have a list [1, 1, 1, 1]
. I need a way to check IF every element within this list are all equal return yes otherwise return no
without using any of the built-in predicates.
list(3,3)
-->> yes , list(3,3,6)
-->> no
I came up with this rule but it doesn't work
equal([E1,E2|T]):- E1=:=E2,
equal([E2,E3|T]).
Upvotes: 1
Views: 216
Reputation: 72356
That E3
appeared out of nowhere. I think you want
equal([]).
equal([X]).
equal([E1,E2|T]) :-
E1 =:= E2,
equal([E2|T]).
Upvotes: 1
Reputation: 10102
Usually, such a predicate is defined using general equality, not arithmetic equality:
equal(Xs) :-
maplist(=(_), Xs).
Is probably the most insightful definition. This uses maplist/2
commonly defined as
maplist(_, []).
maplist(C, [E|Es]) :-
call(C, E),
maplist(C, Es).
Otherwise:
equal(Xs) :-
equals_to(Xs,_).
equals_to([], _).
equals_to([E|Es], E) :-
equals_to(Es, E).
Upvotes: 5