0

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

false
  • 10,264
  • 13
  • 101
  • 209
Trash
  • 15
  • 5

2 Answers2

1

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.

gusbro
  • 22,357
  • 35
  • 46
  • i was not aware member had that capability, although both answers turned out to be very helpful since i have to do other routines similar to this one. – Trash Jan 04 '12 at 19:30
  • instead of your use of `cut/0` please see [this question](http://stackoverflow.com/questions/8436568/code-for-member-2-with-some-determinism/8437359#8437359) to achieve determinism on the last element. It's what's used in swi and doesn't destruct any behavior. – m09 Jan 04 '12 at 19:46
  • @mog: that is SWI's implementation of member, that OP should use; and the determinism in that predicate is just a trick (i doubt it will work on every prolog implementation) – gusbro Jan 04 '12 at 19:52
0

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).

CapelliC
  • 59,646
  • 5
  • 47
  • 90