I have to write a predicates that sums all the items in a list. The items can be a list with list of list in it. for example,
sum1([1,[2,3],4,[5]],X).
i have some code that SHOULD work, but is giving an arguments are not sufficiently instantiated error. I am very new to prolog but these look alright to me. here is my full code for this predicate (function)
suml([],0).
suml([H|T],X) :- atomic(H),S2 is H + X, suml(T,S2).
suml([H|T],X) :- suml(H,S1), S3 is S1 + X, suml(T,S3).
Change the order of the following two conditions: S2 is H + X, suml(T,S2) and change the way you use is/2. Although this is logic programming, the order of the conditions in a rule matters. Put sum1(T, S2) first because you need S2 to be instantiated before computing the sum. Second, is arithmetically evaluates the right part and unifies it with the left part. So, you actually want to sum S2 and H to get X:
suml([H|T],X) :- atomic(H), suml(T,S2), X is H + S2.
Related
I've encountered a problem when trying to iterate through two dimension array and summing up the lengths of all elements inside in prolog.
I've tried iterating through a simple 1D array and result was just as expected. However, difficulties appeared when I started writing the code for 2D array. Here's my code :
findsum(L):-
atom_row(L, Sum),
write(Sum).
atom_row([Head|Tail], Sum) :-
atom_lengths(Head, Sum),
atom_row(Tail, Sum).
atom_row([], 0).
atom_lengths([Head|Tail], Sum):-
atom_chars(Head, CharList),
length(CharList, ThisLenght),
atom_lengths(Tail, Temp),
Sum is Temp + ThisLenght,
write(ThisLenght).
atom_lengths([], 0).
For example, sum of the elements in array [[aaa, bbbb], [ccccc, dddddd]] should be equal to 18. And this is what I get:
?- findsum([[aaa, bbbb], [ccccc, dddddd]]).
436
false.
The output comes from write(ThisLength) line after each iteration.
Typically it helps (a lot) by splitting the problem into simpeler sub-problems. We can solve the problem, for example, with the following three steps:
first we concatenate the list of lists into a single one-dimension list, for example with append/2;
next we map each atom in that list to the length of that atom, with the atom_length/2 predicate; and
finally we sum up these values, for example with sum_list/2.
So the main predicate looks like:
findsum(LL, S) :-
append(LL, L),
maplist(atom_length, L, NL),
sumlist(NL, S).
Since maplist/3 is a predicate defined in the library(apply), we thus don't need to implement any other predicates.
Note: You can see the implementions of the linked predicates by clicking on the :- icon.
For example:
?- findsum([[aaa, bbbb], [ccccc, dddddd]], N).
N = 18.
The idea is as follows: Suppose I have a list P = [(1,0),(4,3)] or similar. I want to evaluate the polynomial that's defined by this list in the manner: 1X^0 + 4X^3.
To do this, I've written the following:
evaluate(P,X,Y) :- evaluate(P,X,Y,0).
evaluate([],_,S,S).
evaluate([P1,P2|Ps],X,Y,S) :-
S1 is S+P1*X^P2,
evaluate(Ps,X,Y,S1).
Which is supposed to succeed when Y is the sum of the polynomial P, given x=X.
The problem is that when I try and run this code, I get the error:
is/2: Arithmetic: `(',')/2' is not a function
But I have no idea where this is coming from or how to fix it.
I did try splitting the S1 is up in to its segments, but doing that didn't help.
EDIT: Ok, I found out that it's about the way the list is written down. How do I work with tuples in this way within the bounds of Prolog?
Your problem is that your data structure for each item in the list is a tuple as you noted and where you access the values of tuple in the list is not correct.
This
evaluate([P1,P2|Ps],X,Y,S) :-
should be
evaluate([(P1,P2)|Ps],X,Y,S) :-
Notice the parenthesis around P1,P2.
When I run with the change I get
?- evaluate([(1,0),(4,3)],5,Y).
Y = 501.
Also it is common to put the output arguments at the end,
evaluate_01(P,X,Y,0).
as
evaluate_01(P,X,0,Y).
and then change the other predicates as necessary.
evaluate_02(P,X,Y) :- evaluate_02(P,X,0,Y).
evaluate_02([],_,S,S).
evaluate_02([(P1,P2)|Ps],X,S,Y) :-
S1 is S+P1*X^P2,
evaluate_02(Ps,X,S1,Y).
As an interesting option, this can be done with maplist/3 and sumlist/2:
evaluate_poly(Poly, X, R) :-
maplist(evaluate_term(X), Poly, EvaluatedTerms),
sumlist(EvaluatedTerms, R).
evaluate_term(X, (Coeff, Power), TermValue) :-
TermValue is Coeff * (X ^ Power).
I have written the following in Prolog (I am using version 7.4.0-rc1), trying to define a predicate insertPermutation/2 which is true if and only if both arguments are lists, one a permutation of the other.
delete(X,[X|T],T). % Base case, element equals head.
delete(X,[A|B],[A|C]) :- delete(X,B,C). % And/or repeat for the tail.
insert(X,Y,Z) :- delete(X,Z,Y). % Inserting is deletion in reverse.
insertPermutation([],[]). % Base case.
insertPermutation([H|T],P) :- insertPermutation(Q,T), insert(H,Q,P). % P permutation of T, H inserted.
I have already been made aware that delete is not a good name for the above helper predicate. We are required to write these predicates, and we cannot use the built-in predicates. This is why I wrote the above code in this way, and I chose the name I did (because I first wrote it to delete an element). It is true if and only if the third argument is a list, equal to the list in the second argument with the first instance of the first argument removed.
The insertPermutation predicate recursively tests if P equals a permutation of the tail of the first list, with the head added in any position in the permutation. This way it works to the base case of both being empty lists.
However, the permutation predicate does not behave the way I want it to. For instance, to the query
?- insertPermutation([1,2,2],[1,2,3]).
Prolog does not return false, but freezes. To the query
?- insertPermutation(X,[a,b,c]).
Prolog responds with
X = [a, b, c] ;
X = [b, a, c] ;
X = [c, a, b] ;
X = [a, c, b] ;
X = [b, c, a] ;
X = [c, b, a] ;
after which it freezes again. I see these problems are related, but not how. Can someone point out what case I am missing?
Edit: Two things, this is homework, and I need to solve this problem using an insert predicate. I wrote this one.
The answer is to change the last line
% P permutation of T, H inserted.
insertPermutation([H|T],P) :-
insertPermutation(Q,T),
insert(H,Q,P).
% P permutation of T, H inserted.
insertPermutation(P,[H|T]) :-
insertPermutation(Q,T),
insert(H,Q,P).
The use cases only needed to check if the first element is a permutation of the latter, not the other way around (or vice versa). Anti-climatic, but the answer to my problem.
I have a clause like following:
lock_open:-
conditional_combination(X),
equal(X,[8,6,5,3,6,9]),!,
print(X).
this clause succeed. But I want to know how many times conditional_combination() is called before equal(X,[8,6,5,3,6,9]) is become true. the program is to generate a permutation by following some rules. And I need to how many permutation is need to generate to get a particular value like 865369.
What you actually want is something slightly different: You want to count the number of answers (so far) of a goal.
The following predicate call_nth(Goal_0, Nth) succeeds like call(Goal_0) but has an additional argument which indicates that the answer found is the n-th answer. This definition is highly specific to SWI or YAP. Do not use things like nb_setarg/3 in your general programs, but use them for well encapsulated cases as this one. Even within
those two systems, the precise meaning of these constructs is not well defined for the general case. Here is a definition for SICStus. Update: use unsigned_64 in newer versions instead of unsigned_32.
call_nth(Goal_0, Nth) :-
nonvar(Nth),
!,
Nth \== 0,
\+arg(Nth,+ 1,2), % produces all expected errors
State = count(0,_), % note the extra argument which remains a variable
Goal_0,
arg(1, State, C1),
C2 is C1+1,
( Nth == C2
-> !
; nb_setarg(1, State, C2),
fail
).
call_nth(Goal_0, Nth) :-
State = count(0,_), % note the extra argument which remains a variable
Goal_0,
arg(1, State, C1),
C2 is C1+1,
nb_setarg(1, State, C2),
Nth = C2.
A more robust abstraction is provided by Eclipse:
call_nth(Goal_0, Nth) :-
shelf_create(counter(0), CounterRef),
call(Goal_0),
shelf_inc(CounterRef, 1),
shelf_get(CounterRef, 1, Nth).
?- call_nth(between(1,5,I),Nth).
I = Nth, Nth = 1
; I = Nth, Nth = 2
; I = Nth, Nth = 3
; I = Nth, Nth = 4
; I = Nth, Nth = 5.
So simply wrap it around:
lock_open :-
call_nth(conditional_combination(X), Nth),
X = [8,6,5,3,6,9],
!,
....
If you are using SWI prolog you can use nb_getval/2 and nb_setval/2 to achieve what you want:
lock_open:-
nb_setval(ctr, 0), % Initialize counter
conditional_combination(X),
nb_inc(ctr), % Increment Counter
equal(X,[8,6,5,3,6,9]),
% Here you can access counter value with nb_getval(ctr, Value)
!,
print(X).
nb_inc(Key):-
nb_getval(Key, Old),
succ(Old, New),
nb_setval(Key, New).
Other prologs have other means to do the same, look for global variables in your prolog implementation. In this snippet I used the term ctr to hold the current goal counter. You can use any term there that is not used in your program.
While working on a module "micro", I recently invented pivots. They are inspired by the thread / pipe pattern to pass around data. A pivot is a bounded queue of maximum length one, the pivot_put/1 does a copy of the given term as well. But for performance reasons they don't use a synchronized and are non-blocking.
In as far they are very similar to nb_setarg/3, except that they don't destruct a Prolog term, but instead they update a Java data structure. As a result they are little bit safer than the non-logical term operations. Also they don't need some call_cleanup/3, since they are Java garbage collected.
In as far they are more similar than nb_setarg/3, than using some explicit allocate and dealloccate of structures. So for example a solution for SICStus Prolog could be:
call_nth(Goal_0, Nth) :-
new(unsigned_32, Counter),
call_cleanup(call_nth1(Goal_0, Counter, Nth),
dispose(Counter)).
call_nth1(Goal_0, Counter, Nth) :-
call(Goal_0),
get_contents(Counter, contents, Count0),
Count1 is Count0+1,
put_contents(Counter, contents, Count1),
Nth = Count1.
With pivots, there is even no 32-bit limitation, and we can directly do:
call_nth(G, C) :-
pivot_new(P),
pivot_put(P, 0),
call(G),
pivot_take(P, M),
N is M+1,
pivot_put(P, N),
C = N.
how can I accomplish this:
Give a tail-recursive definition for each of the following predicates.
power(X,Y,Z): XY=Z.
gcd(X,Y,Z): The greatest common divisor of X and Y is Z.
sum(L,Sum): Sum is the sum of the elements in L.
so far I have done this but not sure if that's correct
power(_,0,1) :- !.
power(X,Y,Z) :- Y1 is Y - 1,power(X,Y1,Z1),Z is X * Z1.
sum(void,0).
sum(t(V,L,R),S) :- sum(L,S1),sum(R,S2), S is V + S1 + S2.
These are not tail recursive. You can write tail recursive variants by using an accumulator, see this answer.
Your sum is over a tree, which is unusual, normally one would use a list. In Prolog [] is the empty list and [X|R] is the pattern for a nonempty list with the head X and the tail R.