2

How to call a list of list in Prolog for exemple I have this list :

list([[1,2,3],[4,5],[6,7]]).

I want to call my list in the element_at function :

element_at(X,[X|_],1).
element_at(X,[_|L],K) :-
   element_at(X,L,K1),
   K is K1 + 1.

When i call

element_at(X,list,2)

I don't have a result.

false
  • 10,264
  • 13
  • 101
  • 209
etudiant
  • 35
  • 1
  • 7

2 Answers2

2

I don't have a result.

Well, you do have a result: failure. But you expected success. Here is a very general method how you can locate such errors in Prolog yourself:

If you encounter unexpected failure, simply generalize your program.

In your particular case, element_at(X,list,2) fails. Maybe it should be 3 in place of 2? Or maybe another number? There is an easy way of guessing in Prolog: Simply replace 3 by a variable! By the same token, you can remove goals in your definition. I will use * to mark those.

Here is a generalization of your program that still fails — and thus there must be an error in the remaining part:

:- op(950, fy, *).
*(_).

?- element_at(X, list, _/*2*/).

element_at(X,[_/*X*/|_],_/*1*/).
element_at(X,[_|L],K) :-
   * element_at(X,L,K1),
   * K is K1 + 1.
false
  • 10,264
  • 13
  • 101
  • 209
0

We retrieve a value from our knowledge base by a call to a predicate,

list(L)

so the whole query at the prompt is

list(L), element_at(X, L, 2).

Or define it in a source file,

my_query(X) :- list(L), element_at(X, L, 2).
Will Ness
  • 70,110
  • 9
  • 98
  • 181