Reputation: 15
I want to return all elements in a list like the result below in X
?return_list_members([1,2,3,4,5], X).
X = 1 ;
X = 2 ;
X = 3 ;
X = 4 ;
X = 5.
I have the following code but it also returns the empty list element [] witch is not desirable.
return_member(X, X).
return_list_members([], []).
return_list_members([H|T], X) :- return_member(H, X); return_list_members(T, X).
output when questioned
?return_list_members([1,2,3,4,5], X).
X = 1 ;
X = 2 ;
X = 3 ;
X = 4 ;
X = 5 ;
X = [].
also the true or false at the end values are not desirable at the end.
The goal is to achieve a function witch outputs like the built-in function between/3 to be used in a foreach statement
Upvotes: 0
Views: 1564
Reputation: 60024
I tried to write between_/3:
between_(X, X, X) :-
!.
between_(X, Y, X) :-
X < Y.
between_(X, Y, N) :-
X < Y,
T is X + 1,
between_(T, Y, N).
The first clause it's required to avoid the final false (as already noticed by gusbro).
Upvotes: 0
Reputation: 22585
Note that the procedure you are trying to write is the builtin predicate member/2.
?- member(X, [1,2,3,4,5]).
X = 1 ;
X = 2 ;
X = 3 ;
X = 4 ;
X = 5.
You can also write your own definition, e.g.:
return_list_members([X|_], X).
return_list_members([_|T], X):-
return_list_members(T, X).
and if you don't want the interpreter to return 'false' at the end, you can add another clause at the beginning (as the first clause):
return_list_members([X], X):- !.
Note however that this clause will have side effects if you call this procedure with the first parameter uninstantiated.
Upvotes: 1