Вопрос

Ok, let's say i have these two facts:

data1([50, 20, 15, 20, 25, 20, 84]). data2([50, 30, 15, 5, 10, 18, 60]).

I want to make a query that asks whether the N-th element of the list defined as a part of those facts is some value.

query([L1|Tail]) :- L1 is 50. This would work but only if the query is like that - query([50, 30, 20]).. I want to ask something like query(data1).

Это было полезно?

Решение

CapelliC's answer is correct, and he discusses why you should use the built-in nth/3 or however it is called (nth1/3 is actually not ISO, and not available in some implementations, like GNU-Prolog). I just want to add some clarification:

Your first issue here is that to ask a question, "does the Nth element of a list have a certain value", you need two arguments already: N and Value. Also, is is a predicate for evaluating arithmetic expressions and cannot be used for your purpose.

As for the query(data1), you need some form of meta-calling....

In summary:

% query(Fact, N, Value) is true
% when the Nth element of the list argument of Fact is Value
query(Fact, N, Value) :-
    call(Fact, List),
    nth(N, List, Value).

and it can be called like this:

?- query(data1, 3, 15).

to query all data1 facts that have one argument, a list.

Here nth should be defined as:

nth(N, List, Value) is true when Value is the Nth element of List

but you should really rather use the built-in available in the implementation you are using.

Другие советы

You can use nth1/3 to access list elements by index.

Note in documentation that it's declared as nth1(?Index, ?List, ?Elem). That question mark on a parameter indicates that that argument could be unbound. In other words, nth1/3 can work in several ways.

To get an element at index (1 based):

?- data1(L), nth1(2, L, V).
L = [50, 20, 15, 20, 25, 20, 84],
V = 20.

or to search positions where an element is:

?- data1(L), nth1(P, L, 20).
L = [50, 20, 15, 20, 25, 20, 84],
P = 2 ;
L = [50, 20, 15, 20, 25, 20, 84],
P = 4 ;
L = [50, 20, 15, 20, 25, 20, 84],
P = 6 ;
false.

It works as generally as possible, faithful to Prolog model where we don't have functions, but relations.

nth1/3 it's a relation between list elements and indexes.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top