prolog list keeps expanding when semi colon is pressed - prolog

Hi I am creating a predicate list from, which if used gives you the numbers between a certain range. So say for instance
list_from(1,5,X).
would give you
X=[1,2,3,4,5].
However I got my predicate to work, but the list just keeps expanding, so it keeps increasing my one and I do not want it to. This is what is happening.
?- list_from(1,7,X).
X = [1, 2, 3, 4, 5, 6, 7] ;
X = [1, 2, 3, 4, 5, 6, 7, 8] ;
X = [1, 2, 3, 4, 5, 6, 7, 8, 9] ;
X = [1, 2, 3, 4, 5, 6, 7, 8, 9|...] ;
X = [1, 2, 3, 4, 5, 6, 7, 8, 9|...]
How do I get this to stop?
Here is my code
list_from(M,N,[]):- M > N.
list_from(M,N,[M|T]):- Mplusone is M + 1, list_from(Mplusone,N,T).
if I remove Mplusone and just M instead I get an error "Out of global stack"

Your two clauses are not mutually exclusive. You have a "guard" in the first clause saying that M > N, but you don't have the opposite condition, M =< N, in the second clause. If you trace the execution you should get an idea of what happens with your current definition.
You might also try to look at the definition of numlist/3 in SWI-Prolog's library(lists). It takes a different approach: first, make sure that the arguments make sense; then, under the condition that the initial Low is indeed lower than High (and both are integers), generate a list.

Semicolon means that you want Prolog to show you more options (that you are not satisfied with the answer). A full stop '.' will stop Prolog from providing you with alternatives.
You could also invoke list_from/3 using once/1. (Credit to #mat)

Related

Prolog Skip some backtracking branches

I'm trying to generate some Kakuros, generate not solve.
I have all rules to generate it, but the firsts results are senseless, those are like squares.
Now I want to skip some branches, 15000 for example, to see the kakuro generated at that point.
I have tried with an Auxiliary Variable, but when it fails, the Kakuro Generator start again.
You can keep a dynamic counter-like predicate in the knowledge base that gets increased every time the main predicate is executed. The value of the counter is changed with assert and retract, i.e., it is not a variable within your main predicate but a globally stored value.
Within your main predicate, if you add the condition that the counter should be higher than some skip value, then you force backtracking over the actual rules for a specified number of iterations.
As an example, consider the built-in predicate permutation/2 which computes permutations of a list (note: tested using SWI-Prolog, other interpreters have different built-in predicates). Example output:
?- permutation([1,2,3,4,5],L).
L = [1, 2, 3, 4, 5] ;
L = [1, 2, 3, 5, 4] ;
L = [1, 2, 4, 3, 5] ;
L = [1, 2, 4, 5, 3] ;
L = [1, 2, 5, 3, 4] ;
L = [1, 2, 5, 4, 3] ;
If you want to skip the first 5 iterations in your query, you can use the following code:
:- dynamic iteration_nr/1.
iteration_nr(0).
get_permutations(L1,L2,Skip) :-
permutation(L1,L2),
iteration_nr(N),
N2 is N+1,
retract(iteration_nr(N)),
asserta(iteration_nr(N2)),
Skip < N2. % force backtracking here if counter < Skip
Example output:
?- get_permutations([1,2,3,4,5],L2,5).
L2 = [1, 2, 5, 4, 3] ;
L2 = [1, 3, 2, 4, 5] ;
L2 = [1, 3, 2, 5, 4]
Note that asserta is used here (i.e., assert at the start) instead of plain assert, which is deprecated. Note also that the counter will keep the value, so when you run this a second time in the same session the results will be different. To reset the counter you can use a separate initialization predicate, for example:
init_and_get_permutations(L1,L2,Skip) :-
retractall(iteration_nr(_)),
asserta(iteration_nr(0)),
get_permutations(L1,L2,Skip).
Further note: the use of assert and retract is not really considered 'clean' Prolog programming, because it is procedural and changes the knowledge base. However, for some applications it can be useful.

List manipulation with prolog

I am trying to create a query that gives back the following:
sky([1,2,3,4,5,6],X).
X = [1,3,5,2,6,4]
That is, it takes out every other element of a list, and does the same on the remaining list and puts everything together.
This is my code so far.
sky([X|Y], Skied):-
split([X|Y],Z1),
split(X,Z2),
sky(Z2,Z3),
append(Z1,Z3,Skied).
sky([],[]).
split([X,_|T], [X|R]):-
split(T,R).
split([X|[]], [X]).
split([],[]).
Can someone explaint o me why it wont work and the process behind it, like a visual guide. Thanks!
Your code is almost right, instead of split(X,Z2) you need to write split(Y,Z2). That's because X is a single element and split(X,Z2) will return [X], which if I understood correctly isn't what you want. You need to write split(Y,Z2) to take the even elements (or in your description every other element) and call sky(Y,Z3) to do the same recursively. So the new version is:
sky([X|Y], Skied):-
split([X|Y],Z1),
split(Y,Z2),
sky(Z2,Z3),
append(Z1,Z3,Skied).
sky([],[]).
split([X,_|T], [X|R]):-
split(T,R).
split([X|[]], [X]).
split([],[]).
Some examples and output:
?- sky([1,2,3,4,5,6],X).
X = [1, 3, 5, 2, 6, 4] ;
false.
?- sky([1,2,3,4,5,6,7,8,9],X).
X = [1, 3, 5, 7, 9, 2, 6, 4, 8] ;
false.

sorting prolog algorithm ¿overflow? [duplicate]

I'm using SWI-Prolog and I'm trying to print a list but if the list has more than 9 items - it look like that -
[1, 15, 8, 22, 5, 19, 12, 25, 3|...]
is there a way to show the whole list?
Have a look at: http://www.swi-prolog.org/FAQ/AllOutput.html
The simple solution is to type w after the answer is given, i.e.:
?- n_queens_problem(10,X).
X = [1, 3, 6, 8, 10, 5, 9, 2, 4|...] [write]
X = [1, 3, 6, 8, 10, 5, 9, 2, 4, 7]
After you have pressed the "w"-key "[write]" is displayed at the end and the full solution appears in the next line.
I've found two ways.
1.
?- set_prolog_flag(answer_write_options,[max_depth(0)]).
true.
Then do your command that is printing a truncated list.
(set_prolog_flag documentation)
2.
?- atom_chars(goodbye_prolog, X) ; true.
(AllOutput documentation)
Put ; true. at the end of the call that results in a long list. Then push the w key on your keyboard. The result is:
?- sudoku([_,_,2,3,_,_,_,_,_,_,_,_,3,4,_,_], Solution); true.
Solution = [4, 1, 2, 3, 2, 3, 4, 1, 1|...] [write]
Solution = [4, 1, 2, 3, 2, 3, 4, 1, 1, 2, 3, 4, 3, 4, 1, 2] ;
true.
If prolog returns only one answer, you can make it wait by typing "; true." after the predicate. Then, if you press "w", you will get to see the whole list as written in the doc : http://www.swi-prolog.org/FAQ/AllOutput.html
?- createListSomehow(List), print(List), nl.
will do it neatly enough. That's what I do.
Variation:
?- use_module(library(pprint)). %load a library to do pretty-printing
?- createListSomehow(List), print_term(List,[]), nl.
The [] argument to print_term is an (empty) list of options. For more information, see documentation.
If you want that SWI-Prolog will show the whole list by default you can add this line to your init file:
:- set_prolog_flag(answer_write_options,[max_depth(0)]).
You can modify the init file easily from the GUI (Settings => User init file).

Eliminate a X element on a list

I have the following knowledge base
eliminate(X,[X|T],T).
eliminate(X,[H|T],[H|T2]) :- eliminate(X,T,T2).
And I have to make the running process of an example by myself, without the interpreter (like a tree).
For example, if I post the query: eliminate(3,[1,2,3,4,5],Y).
First using the first fact, we unificate X=3, and with the second element, which is a list([1,2,3,4,5]) we try to unify 1 with X, but we can't because X now is 3, so it fails and we try with the second rule.
eliminate(3,[1,2,3,4,5],Y).
x = 3, H = 1, T = [2,3,4,5], H = Y , T2 = []
This it the part that I am not sure is right. I don't know why T2 has to be unified with [].
Now with the body clause of the second rule: eliminate(X,T,T2), I have:
eliminate(3,[2,3,4,5],[])
x = 3, (here it fails again, so i have to use the second rule)
eliminate(3,[2,3,4,5],[])
x = 3, H = 2, T = [3,4,5], H = Y, T2 =[] ??? is T2 null again???
T2 doesn't unify with [] the first time the second rule is applied. The resolution knows it is a list (because its on the right side of the [X|Y] construct), but doesn't know its value yet. To find its value, it will first compute the rule, which will find a value for T2 recursively, then unify this value with the Y you ran in your query.
In your example, running the query eliminate(3, [1, 2, 3, 4, 5], Y). will do the following:
Call eliminate(3, [1, 2, 3, 4, 5], Y)
2nd rule: X=3, H=1, T=[2,3,4,5], T2=?, Y=[H|?]
Call eliminate(3, [2, 3, 4, 5], ?)
2nd rule: X=3, H=2, T=[3,4,5], T2=??, Y=[H|??]
Call eliminate(3, [3, 4, 5], ??)
1st rule: ??=[4, 5]
Go back one step, using Y=[H|??], H=2 ??=[4,5]: Y = [2|[4,5]] = [2, 4, 5] = ?
Go back another step, using Y=[H|?], H=1, ?=[2, 4, 5]: Y = [1|[2, 4, 5]] = [1, 2, 4, 5]
I suggest spending some time reading the recusion chapter of your Prolog learning source. Additionally, to find out how you can see this execution in practice to see what's happening, you can use the trace. "command" or other debug equivalent, see this link for swi-pl specifics on debugging a program.

PROLOG List filter predicate not aswering true or false

I'm trying to make a predicate that takes two vectors/lists and uses the first one as a filter. For example:
?- L1=[0,3,0,5,0,0,0,0],L2=[1,2,3,4,5,6,7,8],filter(L1,L2,1).
L1 = [0, 3, 0, 5, 0, 0, 0, 0],
L2 = [1, 2, 3, 4, 5, 6, 7, 8] .
That's what I'm getting but I would want true or false if L2 has 3 as the second element, 5 as the fourth element, etc. The 0s are ignored, that's the "filter" condition.
What I know from the input is that L1 and L2 are always length=8 and only L1 has 0s.
My code is:
filter(_,_,9).
filter([Y|T],V2,Row):-
Y=:=0,
NewRow is Row + 1,
filter([Y|T],V2,NewRow).
filter([Y|T],V2,Row):-
Y=\=0,
nth(Row,[Y|T],X1),
nth(Row,V2,X2),
X1=:=X2,
NewRow is Row + 1,
filter([Y|T],V2,NewRow).
nth(1,[X|_],X).
nth(N,[_|T],R):- M is N-1, nth(M,T,R).
I know there are better ways of doing the function, for example comparing the first element of the first to the nth of the second and delete the head of the first with recursion but I just want to know why I'm not getting true or false, or any "return" value at all.
Can someone help me?, got it working
New code:
filter([],R,_,R).
filter([Y|T],V2,Row,R):-
Y=:=0,
NewRow is Row + 1,
filter(T,V2,NewRow,R).
filter([Y|T],V2,Row,R):-
Y=\=0,
nth(Row,V2,X2),
Y=:=X2,
NewRow is Row + 1,
filter(T,V2,NewRow,R).
Example of expected behaviour:
permutation([1,2,3,4,5,6,7,8],X),filter([1,2,3,4,0,0,0,0],X,1,R).
X = R, R = [1, 2, 3, 4, 5, 6, 7, 8] ;
X = R, R = [1, 2, 3, 4, 5, 6, 8, 7] ;
X = R, R = [1, 2, 3, 4, 5, 7, 6, 8] ;
X = R, R = [1, 2, 3, 4, 5, 7, 8, 6] .
Now i can get all the permutations that starts with 1,2,3,4.
If someone knows a better way to achieve the same, plz share, but i already got what i needed =).
seems like could be a perfect task for maplist/3
filter(L1, L2, _) :-
maplist(skip_or_match, L1, L2).
skip_or_match(E1, E2) :- E1 == 0 ; E1 == E2.
yields
?- permutation([1,2,3,4,5,6,7,8],X),filter([1,2,3,4,0,0,0,0],X,_).
X = [1, 2, 3, 4, 5, 6, 7, 8] ;
X = [1, 2, 3, 4, 5, 6, 8, 7] ;
X = [1, 2, 3, 4, 5, 7, 6, 8] ;
X = [1, 2, 3, 4, 5, 7, 8, 6] ;
...
We could do that more useful, using Prolog facilities - namely, use an anonymus variable to express don't care.
Then filter/N is a simple application of maplist:
?- permutation([1,2,3,4,5,6,7,8],X),maplist(=,[1,2,3,4,_,_,_,_],X).
X = [1, 2, 3, 4, 5, 6, 7, 8] ;
X = [1, 2, 3, 4, 5, 6, 8, 7] ;
X = [1, 2, 3, 4, 5, 7, 6, 8] ;
X = [1, 2, 3, 4, 5, 7, 8, 6] ;
...
Your code always tests the first item of the filtering list for being zero. For example, look at the case when you're checking second value:
filter([0,3,0,5,0,0,0,0], [1,2,3,4,5,6,7,8], 2).
This call will perform the following unifications:
# first case: obvious fail…
filter([0,3,0,5,0,0,0,0], [1,2,3,4,5,6,7,8], 2) =\= filter(_, _, 9).
# second case:
filter([0,3,0,5,0,0,0,0], [1,2,3,4,5,6,7,8], 2) = filter([Y|T],V2,Row).
# unification succeeds with substitutions:
Y = 0
T = [3,0,5,0,0,0,0]
V2 = [1,2,3,4,5,6,7,8]
Row = 2
# and what happens next?
Y =:= 0 # success!
You probably wanted here to check whether second element of [Y|T] is zero; instead, you're checking the first one. If you want to fix it without changing the rest of your code, you should instead perform comparisons to X1:
filter(V1,V2,Row):-
nth(Row, V1, X1),
X1 =:= 0,
NewRow is Row + 1,
filter(V1,V2,NewRow).
filter(V1,V2,Row):-
nth(Row,V1,X1),
X1=\=0,
nth(Row,V2,X2),
X1=:=X2,
NewRow is Row + 1,
filter(V1,V2,NewRow).
Also, there's one more thing that I think you might not be getting yet in Prolog. If a predicate fails, Prolog indeed prints false and stops computation. But if a predicate succeeds, there are two cases:
If there were no variables in your query, Prolog prints true.
If there were any variables in your query, Prolog does not print true. Instead, it prints values of variables instead. This also counts as true.
In your case Prolog actually “returns” true from your predicate—except that because you have used variables in your query, it printed their value instead of printing true.

Resources