It seems to me that you asked for foreach/2
:
?- length(L,Len), foreach(between(1,Len,N),nth1(N,L,N)).
L = [],
Len = 0 ;
L = [1],
Len = 1 ;
L = [1, 2],
Len = 2 ;
L = [1, 2, 3],
Len = 3 ;
L = [1, 2, 3, 4],
Len = 4 ;
L = [1, 2, 3, 4, 5],
Len = 5 ;
L = [1, 2, 3, 4, 5, 6],
Len = 6 ;
L = [1, 2, 3, 4, 5, 6, 7],
Len = 7
?- L=[A,A,A], length(L,Len), foreach(between(1,Len,N),nth1(N,L,N)).
false.
?- L=[A,B,C], length(L,Len), foreach(between(1,Len,N),nth1(N,L,N)).
L = [1, 2, 3],
A = 1,
B = 2,
C = Len, Len = 3.
For the name example - in the real world this would of course be much simpler:
funny_word("Clown").
funny_word("Joker").
name_example(FirstName, LastName) :-
funny_word(FirstName),
funny_word(LastName).
But for the sake of the question I think you look for something like this:
name_key(surname).
name_key(forename).
has_name(Key,Value,Names) :-
member(Key-Value, Names).
names(Names) :-
foreach(name_key(Key),
(
funny_word(Name),
has_name(Key,Name,Names)
)).
Example:
?- length(N,_), names(N).
N = [surname-"Clown", forename-"Clown"] ;
N = [forename-"Clown", surname-"Clown"] ;
N = [surname-"Joker", forename-"Joker"] ;
N = [forename-"Joker", surname-"Joker"]
(Note that you need the has_name/3
predicate or something similar, because just plugging in member(Key-Name,Names)
doesn’t work: Foreach bug?