Prolog print value as result instead of true - printing

I need to write a program, which returns a new list from a given list with following criteria.
If list member is negative or 0 it should and that value 3 times to new list. If member is positive it should add value 2 times for that list.
For example :
goal: dt([-3,2,0],R).
R = [-3,-3,-3,2,2,0,0,0].
I have written following code and it works fine for me, but it returns true as result instead of R = [some_values]
My code :
dt([],R):- write(R). % end print new list
dt([X|Tail],R):- X =< 0, addNegavite(Tail,X,R). % add 3 negatives or 0
dt([X|Tail],R):- X > 0, addPositive(Tail,X,R). % add 2 positives
addNegavite(Tail,X,R):- append([X,X,X],R,Z), dt(Tail, Z).
addPositive(Tail,X,R):- append([X,X],R,Z), dt(Tail, Z).
Maybe someone know how to make it print R = [] instead of true.

Your code prepares the value of R as it goes down the recursing chain top-to-bottom, treating the value passed in as the initial list. Calling dt/2 with an empty list produces the desired output:
:- dt([-3,2,0],[]).
Demo #1 - Note the reversed order
This is, however, an unusual way of doing things in Prolog: typically, R is your return value, produced in the other way around, when the base case services the "empty list" situation, and the rest of the rules grow the result from that empty list:
dt([],[]). % Base case: empty list produces an empty list
dt([X|Like],R):- X =< 0, addNegavite(Like,X,R).
dt([X|Like],R):- X > 0, addPositive(Like,X,R).
% The two remaining rules do the tail first, then append:
addNegavite(Like,X,R):- dt(Like, Z), append([X,X,X], Z, R).
addPositive(Like,X,R):- dt(Like, Z), append([X,X], Z, R).
Demo #2

Why do you call write inside your clauses?
Better don't have side-effects in your clauses:
dt([], []).
dt([N|NS], [N,N,N|MS]) :-
N =< 0,
dt(NS, MS).
dt([N|NS], [N,N|MS]) :-
N > 0,
dt(NS, MS).
That will work:
?- dt([-3,2,0], R).
R = [-3, -3, -3, 2, 2, 0, 0, 0] .
A further advantage of not invoking functions with side-effects in clauses is that the reverse works, too:
?- dt(R, [-3, -3, -3, 2, 2, 0, 0, 0]).
R = [-3, 2, 0] .
Of cause you can invoke write outside of your clauses:
?- dt([-3,2,0], R), write(R).
[-3,-3,-3,2,2,0,0,0]
R = [-3, -3, -3, 2, 2, 0, 0, 0] .

Related

Z3 - how to count matches?

I have a finite set of pairs of type (int a, int b). The exact values of the pairs are explicitly present in the knowledge base. For example it could be represented by a function (int a, int b) -> (bool exists) which is fully defined on a finite domain.
I would like to write a function f with signature (int b) -> (int count), representing the number of pairs containing the specified b value as its second member. I would like to do this in z3 python, though it would also be useful to know how to do this in the z3 language
For example, my pairs could be:
(0, 0)
(0, 1)
(1, 1)
(1, 2)
(2, 1)
then f(0) = 1, f(1) = 3, f(2) = 1
This is a bit of an odd thing to do in z3: If the exact values of the pairs are in your knowledge base, then why do you need an SMT solver? You can just search and count using your regular programming techniques, whichever language you are in.
But perhaps you have some other constraints that come into play, and want a generic answer. Here's how one would code this problem in z3py:
from z3 import *
pairs = [(0, 0), (0, 1), (1, 1), (1, 2), (2, 1)]
def count(snd):
return sum([If(snd == p[1], 1, 0) for p in pairs])
s = Solver()
searchFor = Int('searchFor')
result = Int('result')
s.add(Or(*[searchFor == d[0] for d in pairs]))
s.add(result == count(searchFor))
while s.check() == sat:
m = s.model()
print("f(" + str(m[searchFor]) + ") = " + str(m[result]))
s.add(searchFor != m[searchFor])
When run, this prints:
f(0) = 1
f(1) = 3
f(2) = 1
as you predicted.
Again; if your pairs are exactly known (i.e., they are concrete numbers), don't use z3 for this problem: Simply write a program to count as needed. If the database values, however, are not necessarily concrete but have other constraints, then above would be the way to go.
To find out how this is coded in SMTLib (the native language z3 speaks), you can insert print(s.sexpr()) in the program before the while loop starts. That's one way. Of course, if you were writing this by hand, you might want to code it differently in SMTLib; but I'd strongly recommend sticking to higher-level languages instead of SMTLib as it tends to be hard to read/write for anyone except machines.

maxima (macsyma): KKT conditions

I fancy using maxima to explore a certain quadratic problem
with linear constraints and inequalities.
Namely, I have the following set of maxima-instructions, spelling the KKT constraints:
f(a11,a12,a13,a21,a22,a23,a31,a32,a33):=(1-a11)**2*(1-q1)*q1+a12**2*(1-q2)*q2+a13*(1-q3)*q3+a21*(1-q1)*q1+(1-a22)**2*(1-q2)*q2+a23**2*(1-q3)*q3+a31**2*(1-q1)*q1+a32**2*(1-q2)*q2+(1-a33)**2*(1-q3)*q3;
F:f(a11,a12,a13,a21,a22,a23,a31,a32,a33);
g1(a11,a12,a13,a21,a22,a23,a31,a32,a33):=(q1*a11+q2*a12+q3*a13)-q1;
G1:g1(a11,a12,a13,a21,a22,a23,a31,a32,a33);
g2(a11,a12,a13,a21,a22,a23,a31,a32,a33):=(q1*a21+q2*a22+q3*a23)-q2;
G2:g2(a11,a12,a13,a21,a22,a23,a31,a32,a33);
h1(a11,a12,a13,a21,a22,a23,a31,a32,a33):=a11+a21+a31-1;
H1:h1(a11,a12,a13,a21,a22,a23,a31,a32,a33);
h2(a11,a12,a13,a21,a22,a23,a31,a32,a33):=a12+a22+a32-1;
H2:h2(a11,a12,a13,a21,a22,a23,a31,a32,a33);
h3(a11,a12,a13,a21,a22,a23,a31,a32,a33):=a13+a23+a33-1;
H3:h3(a11,a12,a13,a21,a22,a23,a31,a32,a33);
KKT(a11,a12,a13,a21,a22,a23,a31,a32,a33,lambda1,lambda2,lambda3,lambda4,lambda5,mu11,mu12,mu13,mu21,mu22,mu23,mu31,mu32,mu33):=F+lambda1*G1+lambda2*G2+lambda3*H1+lambda4*H2+lambda5*H3-mu11*a11-mu12*a12-mu13*a13-mu21*a21-mu22*a22-mu23*a23-mu31*a31-mu32*a32-mu33*a33;
kkt:KKT(a11,a12,a13,a21,a22,a23,a31,a32,a33,lambda1,lambda2,lambda3,lambda4,lambda5,mu11,mu12,mu13,mu21,mu22,mu23,mu31,mu32,mu33);
gradF : jacobian([kkt],[a11,a12,a13,a21,a22,a23,a31,a32,a33,lambda1,lambda2,lambda3,lambda4,lambda5,mu11,mu12,mu13,mu21,mu22,mu23,mu31,mu32,mu33])[1];
orthogonality_constraints : [mu11*a11 = 0, mu12*a12 = 0, mu13*a13 = 0, mu21*a21 = 0, mu22*a22 = 0, mu23*a23 = 0, mu31*a31 = 0, mu32*a32 = 0, mu33*a33 = 0];
Here, we have 9 "original" variables a11,a12,...,a33, and 2+3 = 5 constraints expressed as G1,G2,H1,H2,H3 in the above piece of code.
We would like to impose non-negativity conditions on a11,a12,...,a33,
and therefore I would like to write something like
solve([gradF,G1,G2,H1,H2,H3,orthogonality_constraints],[a11,...,a33,lambda1,...,lambda5,mu11,...,mu33]).
However, orthogonality_constraints needs to somehow be "unwrapped", I guess, before putting it inside the first argument of solve(). Same for gradF.
How to do this?
Maybe flatten
e: [gradF,G1,G2,H1,H2,H3,orthogonality_constraints] $
e: flatten(e) $
solve(e, [...]);
From ?flatten;
Applied to a list, 'flatten' gathers all list elements that are
lists.
(%i1) flatten ([a, b, [c, [d, e], f], [[g, h]], i, j]);
(%o1) [a, b, c, d, e, f, g, h, i, j]

How do I get Maxima to store function output?

I have the logistic map function in Maxima like so:
F(x,r,n):= x[n]=r*x[n-1]*(1-x[n-1]);
And when I input the correct variables it gives me the answer to, for example, x[0]:
(%i15) n:0$
x[n-1]:[0.1]$
F(x, r:3, n);
(%o15) x[0]=[0.27]
However, this answer does not stay memorized and when I enter x[0] I get
x[0];
(%o5) x[0]
How do I write a function that will calculate x[n] for me and store it in memory, so I can use it later? I am trying to make a bifurcation diagram for the logistic map without using any black boxes, i.e., the orbits functions.
Thank you!
There are different ways to go about it. One straightforward way is to create a list and then iterate, computing its elements one by one. E.g.:
(%i4) x: makelist (0, 10);
(%o4) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
(%i5) x[1]: 0.1;
(%o5) 0.1
(%i6) r: 3;
(%o6) 3
(%i7) for i:2 thru 10 do x[i]: r * x[i - 1] * (1 - x[i - 1]);
(%o7) done
(%i8) x;
(%o8) [0.1, 0.2700000000000001, 0.5913000000000002,
0.7249929299999999, 0.5981345443500454, 0.7211088336156269,
0.603332651091411, 0.7179670896552621, 0.6074710434816448,
0.7153499244388992]
Note that : is the assignment operator, not =.

How Racket streams work in this case?

I am currently learning Racket (just for fun) and I stumbled upon this example:
(define doubles
(stream-cons
1
(stream-map
(lambda (x)
(begin
(display "map applied to: ")
(display x)
(newline)
(* x 2)))
doubles)))
It produces 1 2 4 8 16 ...
I do not quite understand how it works.
So it creates 1 as a first element; when I call (stream-ref doubles 1) it creates a second element which is obviously 2.
Then I call (stream-ref doubles 2) which should force creating the third element so it calls stream-map for a stream which already has 2 elements – (1 2) – so it should produce (2 4) then and append this result to the stream.
Why is this stream-map always applied to the last created element? How it works?
Thank you for your help!
This is a standard trick that makes it possible for lazy streams to be defined in terms of their previous element. Consider a stream as an infinite sequence of values:
s = x0, x1, x2, ...
Now, when you map over a stream, you provide a function and produce a new stream with the function applied to each element of the stream:
map(f, s) = f(x0), f(x1), f(x2), ...
But what happens when a stream is defined in terms of a mapping over itself? Well, if we have a stream s = 1, map(f, s), we can expand that definition:
s = 1, map(f, s)
= 1, f(x0), f(x1), f(x2), ...
Now, when we actually go to evaluate the second element of the stream, f(x0), then x0 is clearly 1, since we defined the first element of the stream to be 1. But when we go to evaluate the third element of the stream, f(x1), we need to know x1. Fortunately, we just evaluated x1, since it is f(x0)! This means we can “unfold” the sequence one element at a time, where each element is defined in terms of the previous one:
f(x) = x * 2
s = 1, map(f, s)
= 1, f(x0), f(x1), f(x2), ...
= 1, f(1), f(x1), f(x2), ...
= 1, 2, f(x1), f(x2), ...
= 1, 2, f(2), f(x2), ...
= 1, 2, 4, f(x2), ...
= 1, 2, 4, f(4), ...
= 1, 2, 4, 8, ...
This knot-tying works because streams are evaluated lazily, so each value is computed on-demand, left-to-right. Therefore, each previous element has been computed by the time the subsequent one is demanded, and the self-reference doesn’t cause any problems.

How to print square of n*n given characters in prolog?

Write a Prolog program to print out a square of n*n given characters on the screen. Call your predicate square/2. The first argument should be a (positive) integer. the second argument the character (any Prolog term) to be printed. Example:
?-square(5, '*').
*****
*****
*****
*****
*****
Yes
I just start to learn this language. I did this:
square(_,'_').
square(N, 'B') :-
N>0,
write(N*'B').
It doesn't work at all. Can anyone help me?
So your question is, basically, "how do I write a loop nested in a loop?"
This is how you write an empty loop with an integer for a counter:
loop(0).
loop(N) :- N > 0, N0 is N-1, loop(N0).
which in C would be:
for(i=0; i < n; ++i) { }
And you seem to know already how to print (write(foo)).
Decompose the problem. To write an NxN square, you need to do two things:
Write N lines
Write a single line, consisting of N characters followed by a newline character.
The second is easy:
do_line(0,_) :-
nl
.
do_line(N,C) :-
N > 0 ,
write(C) ,
N1 is N-1 ,
do_line(N1,C)
.
The first isn't much more difficult:
do_lines(0,_,_).
do_lines(M,N,C) :-
M > 0 ,
do_line(N,C) ,
M1 is M-1 ,
do_lines(M1,N,C)
.
The all you need to do is wrap it:
write_square(N,C) :- do_lines(N,N,C) .
Easy!
You need to draw a line of N stars/characters
line(N,X):- N>0, N1 is N-1, line(N1,X), write(X), fail; true.
Then you will draw a column of N lines of stars/characters.
s(N,Chr):-sAux(N,0,Chr).
sAux(N,N,Chr).
sAux(N,C,Chr):-C<N, C1 is C+1, sAux(N, C1, Chr), line(N,Chr),nl.
s(N,Chr):- N>0, N1 is N-1, s(N1,X), linie(N,X), nl, fail;true.
Doing this:
square2(0,_). % base case, recursion stops when X reaches 0, second argument is irrelevent
square2(X,Symbol):-
X1 is X - 1,
write(Symbol),
square2(X1,Symbol).
With the query, which results in:
?- square2(5,'* ').
* * * * *
Therefore, we need another loop to make it write X times.
square1(0,_,_). % base case, recursion stops when X reaches 0
square1(X,Y,Symbol):-
X1 is X - 1,
square2(Y,Symbol), % with the same Y passed in square2 predicate to print a line of symbols
nl, % creates a new line
square1(X1,Y,Symbol).
However, the question is asking for the format with square(5, '* '). Therefore,
square(X,Symbol):-
square1(X,X,Symbol).
To wrap up:
square(X,Symbol):-
square1(X,X,Symbol).
square1(0,_,_).
square1(X,Y,Symbol):-
X1 is X - 1,
square2(Y,Symbol),
nl,
square1(X1,Y,Symbol).
square2(0,_).
square2(X,Symbol):-
X1 is X - 1,
write(Symbol),
square2(X1,Symbol).

Resources