1
votes

I am trying to list a given number of elements i have stored in List , my code is as follows

er(Person,List) :- findall(A, descendant(Person, A), List).

when i type the code below into prolog i get all of the elements that match my query.

er(james,X).

What i am trying to achieve is ask prolog to list a given amount of element say for example

er(james,3).

Prolog will only return at most 3 element from the list . I researched a bit and found that i can use findnsols instead of the findall operator but i couldn't find a practical way to implement it in my code .

1
findnsols(3, A, descendant(Person, A), List) should work. Please explain your problem...CapelliC
findnsols is not optimal for me since it requires more than two element trying to keep it at er(X,Y) , the issue i also have with findnsols is i have to include an exact number in the query rather than type it in the program itself . say findnsols(Nth, A, descendant(Person, A), List). the nth can be any number from 0 to 999.user4172072
findnsols(count(N), etc etc) allows to change 'on the fly' the returned list length. But this advanced feature seems beyond your needs. At some point, before calling findnsols, you will know the value Nth, no ? So just use itCapelliC

1 Answers

-1
votes

Well, the obvious way would be to say something like this:

er(P,N,L) :-
  findnsols(N,A,descendant(P,A),L)
  .

But you seem not to want to do that. You might consider something like this:

er(P,L) :-
  var(L),
  findall(A,descendant(P,A),L)
  .
er(P,L) :-
  nonvar(L),
  length(L,N),
  findnsols(N,A,descendant(P,A),L)
  .

If you want all the solutions back, just invoke it like this:

er(james,L).

If you want to limit things, like this:

er(james,[A,B,C]).

or (since length/2 can be generative):

length(5,L) , er(james,L).