Prolog - Arguments insufficiently instantiated - prolog

I am new to prolog, and I have built the following sample function:
bar(Fruit) :-
Fruit = fruit(apple, X),
A is abs(X) + 0,
between(0,10,A).
foo(L) :-
findall(X, bar(fruit(apple, X)), L).
Calling foo(L) gives the error : ERROR: is/2: Arguments are not sufficiently instantiated.
Now, I've read around multiple threads in which the recurring solution is to use clpfd where A #= abs(X) + 0. However, when using that solution I do not necessarily get the list I want :
L = [0, _G9407, _G9410, _G9413, _G9416, _G9419, _G9422, _G9425, _G9428|...],
clpfd:in(_G9407, -1\/1),
clpfd:in(_G9410, -2\/2),
clpfd:in(_G9413, -3\/3),
clpfd:in(_G9416, -4\/4),
clpfd:in(_G9419, -5\/5),
clpfd:in(_G9422, -6\/6),
clpfd:in(_G9425, -7\/7),
clpfd:in(_G9428, -8\/8),
clpfd:in(_G9431, -9\/9),
clpfd:in(_G9434, -10\/10).
Especially when using a more complex function it becomes very hard to read as well.. The output I was expecting is essentially a clear and simple list : [-10...10]. Is there any alternative to this without clpfd? I have also learned through the process that I get the similar errors using logical operators such as <, >, >=, =< which pushes me to use between. I am coming from an OOP background, and I have a hard time grasping what the logical flaw is..
Thanks for the help,

Prolog is mostly relational in the sense that you can often calculate in both directions, but not with maths. is/2 requires that the RHS is a value (no uninstantiated variables). And you cannot use abs(X) to get both +X and -X, which is what you seem to expect. + 0 is not useful, but I guess you have just simplified from something else.
This works:
bar(Fruit) :-
Fruit = fruit(apple, X),
between(0,5,A),
( X = A ; X is -A ).
giving
?- foo(L).
L = [0, 0, 1, -1, 2, -2, 3, -3, 4, -4, 5, -5].
But it sounds like you may want to use CLP(FD) for what you want to do.

Related

Prolog: sum the elements of a list

I am very new to prolog and I'm trying to sum the elements of a list.
So far, I have this:
sum([],_,_). %base case
sum([H|T], Y, _X):-
X2 is H + Y,
sum(T,X2,X2).
testing with sum([1,2,3,4], 0, X) results in an error, but I'm not sure what's wrong with this code. Could someone point me in the right direction?
The code you gave is closer to working than you probably think, but it has a couple problems.
For one, Prolog predicates aren't functions, they don't return results like functions in other languages do. Predicates, instead, declare something about what is true. Later you can give prolog queries and it'll try to make them true.
For example, calls to length/2 are true when the left argument is a list, and the right argument is an int with the length of the list:
?- length([1, 2, 3, 4], 4).
true.
?- length([1, 2, 3, 4], X).
X = 4.
?- length(X, 2).
X = [_2300, _2306].
Looking back at your first line:
sum([],_,_). %base case
This says "sum/3 is always true, as long as the first element is an empty list". You can test this:
?- sum([], -20, hello).
true.
That's probably not what you were intending.
I'm not sure how to put the rest of this without just giving away the answer, but look at what this clause is saying:
sum([H|T], Y, _X):-
X2 is H + Y,
sum(T,X2,X2).
"sum([H|T], Y, WhoCaresIllNeverUseThisVariable) is true if we can recur and prove that sum(T, H+Y, H+Y) is true".
Well, one point, that last argument is a little weird, because in both clauses you assign it to an anonymous variable (_ and _X). What you're saying is, "the third argument never matters and should match literally anything the uses throws at it". I don't think that's what you mean to say.
Second point, I don't know if you realize it but, you're actually computing a sum here! While trying to make sum([1, 2, 3, 4], 0, X) true Prolog will traverse the list and add each element to the middle argument, your accumulator. The summing part works! What you're failing to do is extract the sum from this predicate.
Generally in Prolog you "return" results by making them an additional argument. You could look at length/2 this way. Here's a way you might write it yourself:
my_length([], 0).
my_length([_|Rest], Length) :-
my_length(Rest, Length1),
Length is Length1 + 1.
This function "returns" the length of the array by only being true when the second argument of the predicate is the length of the array.

Does prolog have a spread/splat/*args operator?

In many procedural languages (such as python), I can "unpack" a list and use it as arguments for a function. For example...
def print_sum(a, b, c):
sum = a + b + c
print("The sum is %d" % sum)
print_sum(*[5, 2, 1])
This code will print: "The sum is 8"
Here is the documentation for this language feature.
Does prolog have a similar feature?
Is there a way to replicate this argument-unpacking behaviour in Prolog?
For example, I'd like to unpack a list variable before passing it into call.
Could I write a predicate like this?
assert_true(Predicate, with_args([Input])) :-
call(Predicate, Input).
% Where `Input` is somehow unpacked before being passed into `call`.
...That I could then query with
?- assert_true(reverse, with_args([ [1, 2, 3], [3, 2, 1] ])).
% Should be true, currently fails.
?- assert_true(succ, with_args([ 2, 3 ]).
% Should be true, currently fails.
?- assert_true(succ, with_args([ 2, 4 ]).
% Should be false, currently fails.
Notes
You may think that this is an XY Problem. It could be, but don't get discouraged. It'd be ideal to receive an answer for just my question title.
You may tell me that I'm approaching the problem poorly. I know your intentions are good, but this kind of advice won't help to answer the question. Please refer to the above point.
Perhaps I'm approaching Prolog in too much of a procedural mindset. If this is the case, then what mindset would help me to solve the problem?
I'm using SWI-Prolog.
The built-in (=..)/2 (univ) serves this purpose. E.g.
?- G =.. [g, 1, 2, 3].
G = g(1,2,3).
?- g(1,2,3) =.. Xs.
Xs = [g,1,2,3].
However, note that many uses of (=..)/2 where the number of arguments is fixed can be replaced by call/2...call/8.
First: it is too easy, using unification and pattern matching, to get the elements of a list or the arguments of any term, if you know its shape. In other words:
sum_of_three(X, Y, Z, Sum) :- Sum is X+Y+Z.
?- List = [5, 2, 1],
List = [X, Y, Z], % or List = [X, Y, Z|_] if the list might be longer
sum_of_three(X, Y, Z, Sum).
For example, if you have command line arguments, and you are interested only in the first two command line arguments, it is easy to get them like this:
current_prolog_flag(argv, [First, Second|_])
Many standard predicates take lists as arguments. For example, any predicate that needs a number of options, as open/3 and open/4. Such a pair could be implemented as follows:
open(SrcDest, Mode, Stream) :-
open(SrcDest, Mode, Stream, []).
open(SrcDest, Mode, Stream, Options) :-
% get the relevant options and open the file
Here getting the relevant options can be done with a library like library(option), which can be used for example like this:
?- option(bar(X), [foo(1), bar(2), baz(3)]).
X = 2.
So this is how you can pass named arguments.
Another thing that was not mentioned in the answer by #false: in Prolog, you can do things like this:
Goal = reverse(X, Y), X = [a,b,c], Y = [c,b,a]
and at some later point:
call(Goal)
or even
Goal
To put it differently, I don't see the point in passing the arguments as a list, instead of just passing the goal as a term. At what point are the arguments a list, and why are they packed into a list?
To put it differently: given how call works, there is usually no need for unpacking a list [X, Y, Z] to a conjunction X, Y, Z that you can then use as an argument list. As in the comment to your question, these are all fine:
call(reverse, [a,b,c], [c,b,a])
and
call(reverse([a,b,c]), [c,b,a])
and
call(reverse([a,b,c], [c,b,a]))
The last one is the same as
Goal = reverse([a,b,c], [c,b,a]), Goal
This is why you can do something like this:
?- maplist(=(X), [Y, Z]).
X = Y, Y = Z.
instead of writing:
?- maplist(=, [X,X], [Y, Z]).
X = Y, Y = Z.

Define the predicate Prolog

I'm reviewing some exercise for the coming test and having difficulty at this.
Given a list of integers L, define the predicate: add(L,S) which returns a list of integers S in which each element is the sum of all the elements in L up to the same position.
Example:
?- add([1,2,3,4,5],S).
S = [1,3,6,10,15].
So my question is what define the predicate means? It looks pretty general. I've read some threads but they did not provide much. Thanks!
This is a good exercise to familiarize yourself with two important Prolog concepts:
declarative integer arithmetic to reason about integers in all directions
meta-predicates to shorten your code.
We start with a very simple relation, relating an integer I and a sum of integers S0 to a new sum S:
sum_(I, S0, S) :- S #= S0 + I.
Depending on your Prolog system, you may need a directive like:
:- use_module(library(clpfd)).
to use declarative integer arithmetic.
Second, there is a powerful family of meta-predicates (see meta-predicate) called scanl/N, which are described in Richard O'Keefe's Prolog library proposal, and already implemented in some systems. In our case, we only need scanl/4.
Example query:
?- scanl(sum_, [1,2,3,4,5], 0, Sums).
Sums = [0, 1, 3, 6, 10, 15].
Done!
In fact, more than done, because we can use this in all directions, for example:
?- scanl(sum_, Is, 0, Sums).
Is = [],
Sums = [0] ;
Is = [_2540],
Sums = [0, _2540],
_2540 in inf..sup ;
Is = [_3008, _3014],
Sums = [0, _3008, _3044],
_3008+_3014#=_3044 ;
etc.
This is what we expect from a truly relational solution!
Note also the occurrence of 0 as the first element in the list of partial sums. It satisfies your textual description of the task, but not the example you posted. I leave aligning these as an exercise.
Define the predicate simply means write a predicate that does what the question requires.
In your question you have to write the definition of add/2 predicate( "/2" means that it has two arguments). You could write the definition below:
add(L,S):- add1(L,0,S).
add1([],_,[]).
add1([H|T],Sum,[H1|T1]):- H1 is Sum+H,NSum is Sum+H,add1(T,NSum,T1).
The above predicate gives you the desired output. A simple example:
?- add([1,2,3,4,5],S).
S = [1, 3, 6, 10, 15].
I think the above or something similar predicate is what someone would wait to see in a test.
Some additional information-issues
The problem with the predicate above is that if you query for example:
?- add(S,L).
S = L, L = [] ;
ERROR: is/2: Arguments are not sufficiently instantiated
As you see when you try to ask when your predicate succeeds it gives an obvious solutions and for further solutions it throws an error. This is not a very good-desired property. You could improve that by using module CLPFD:
:- use_module(library(clpfd)).
add(L,S):- add1(L,0,S).
add1([],_,[]).
add1([H|T],Sum,[H1|T1]):- H1 #= Sum+H,NSum #= Sum+H,add1(T,NSum,T1).
Now some querying:
?- add([1,2,3,4,5],S).
S = [1, 3, 6, 10, 15].
?- add(S,[1,3,6]).
S = [1, 2, 3].
?- add(S,L).
S = L, L = [] ;
S = L, L = [_G1007],
_G1007 in inf..sup ;
S = [_G1282, _G1285],
L = [_G1282, _G1297],
_G1282+_G1285#=_G1307,
_G1282+_G1285#=_G1297 ;
...and goes on..
As you can see now the predicate is in the position to give any information you ask! That's because now it has a more relational behavior instead of the functional behavior that it had before due to is/2 predicate. (These are some more information to improve the predicate's behavior. For the test you might not be allowed to use libraries etc... so you may write just a simple solution that at least answers the question).

Creating an Identity Matrix in Prolog

I have to write the predicate identity/2 which receives a number n, and makes an identity matrix [n x n].
Example:
identity(3,I).
I = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
For this one I do not even know how to start. At least an insight on how to build a simple list of n elements could provide me a good starting point! Thank you!
Well, the first thing you need to do is worry about your base case, which I'll just give you:
identity(1, [[1]]).
Now you need to make it work inductively for the rest.
Personally, I would write some helper predicates, like this to produce a list of zeroes:
zeroes(0, []).
zeroes(N, [0|Rest]) :- succ(N0, N), zeroes(N0, Rest).
You can also generate lists of arbitrary size using length/2:
?- length(X, 3).
X = [_G1563, _G1566, _G1569].
Other predicates that might be helpful to you: nth1/3:
?- length(X, 3), nth1(1, X, foo), nth1(3, X, bar).
X = [foo, _G1658, bar].
And don't forget you can prepend to a list just by using [X|Rest]. :) Good luck!

Reification integration issues

I offered the following clpfd-based code for the recent question Segregating Lists in Prolog:
list_evens_odds([],[],[]).
list_evens_odds([X|Xs],[X|Es],Os) :-
X mod 2 #= 0,
list_evens_odds(Xs,Es,Os).
list_evens_odds([X|Xs],Es,[X|Os]) :-
X mod 2 #= 1,
list_evens_odds(Xs,Es,Os).
It is concise and pure, but can leave behind many unnecessary choice-points. Consider:
?- list_evens_odds([1,2,3,4,5,6,7],Es,Os).
Above query leaves behind a useless choice-point for every non-odd item in [1,2,3,4,5,6,7].
Alternative implementation
Using the reification technique demonstrated by #false in Prolog union for A U B U C can reduce the number of unnecessary choice-points. The implementation could change to:
list_evens_odds([],[],[]).
list_evens_odds([X|Xs],Es,Os) :-
if_(#<=>(X mod 2 #= 0), (Es=[X|Es0],Os= Os0),
(Es= Es0, Os=[X|Os0])),
list_evens_odds(Xs,Es0,Os0).
To directly interact with clpfd-reification the implementation of if_/3 could be adapted like this:
if_( C_1, Then_0, Else_0) :-
call(C_1,Truth01),
indomain(Truth01),
( Truth01 == 1 -> Then_0 ; Truth01 == 0, Else_0 ).
Of course, (=)/3 would also need to be adapted to this convention.
The bottom line
So I wonder: Is using 0 and 1 as truth-values instead of false and true a good idea?
Am I missing problems along that road? Help, please! Thank you in advance!
In SWI-Prolog, you can use zcompare/3:
:- use_module(library(clpfd)).
list_evens_odds([], [], []).
list_evens_odds([X|Xs], Es, Os) :-
Mod #= X mod 2,
zcompare(Ord, 0, Mod),
ord_(Ord, X, Es0, Es, Os0, Os),
list_evens_odds(Xs, Es0, Os0).
ord_(=, X, Es0, [X|Es0], Os, Os).
ord_(<, X, Es, Es, Os0, [X|Os0]).
Example query:
?- list_evens_odds([1,2,3,4,5,6,7], Es, Os).
Es = [2, 4, 6],
Os = [1, 3, 5, 7].
I have reconsidered my proposed "double-use" of if_/3 and I feel like I'm seeing better through it now.
The comments by #false and #lurker and the answer by #mat have had their fair share in aiding my understanding. Thank you!
The "insights" I have gained are by no means dramatic; still I'd like to share them with you:
Adapting if_/3 like I did is do-able and may same some LOC's.
However, it mixes up two concepts that are procedurally quite different from each other: By default, clpfd propagates and then delays. Reified term equality OTOH forces a choice right away.
It is therefore cleaner to separate these two use cases. And of course, "Cleanliness is indeed next to Godliness"...
The straightforward solution (which works for any reifiable clp(fd) condition) would seem to be
:- use_module(library(clpfd)).
list_evens_odds([],[],[]).
list_evens_odds([X|Xs],Es,Os) :-
B #<==> (X mod 2 #= 0),
freeze(B, (B=1 -> Es=[X|Es0],Os=Os0 ; Es=Es0,Os=[X|Os0])),
list_evens_odds(Xs,Es0,Os0).
Whether 0/1 or true/false are used as truth values doesn't really matter here. The reason the 0/1 convention is preferred in arithmetic solvers is simply that you can easily reuse the truth values in arithmetic constraints, e.g. add them up, etc.

Resources