|Parse To Prolog Variables Using DCG|
You want to associate ground terms like x (no need to write 'x') with
uninstantiated variables. Certainly that does not constitute a pure
relation. So it is not that clear to me that you actually want this.
And where do you get the list [x, &&, x] in the first place?
You probably have some kind of tokenizer. If possible, try to
associate variable names to variables prior to the actual par
|Most general higher-order constraint describing a sequence of integers ordered with respect to a relation|
Hoogle was not very useful, but Hayoo is!
so this is a special form of fold for a list, but it does not apply
length list times but one time less.
is not entirely general in its name, but in its signature. Maybe
insisting on the most general name is not that helpful. Otherwise we
just have entities all over?
The definition reads:
The isSortedBy function returns True if
|Prolog partial rule matching|
I finally did what i wanted to and it goes like this (swi_prolog)
where rule is the name of rules to check
|Evaluating(interpreting) a list in Prolog|
the simpler code I can think of:
eval([A1,A2,sum|Rest], Result) :- Sum is A1+A2, !, eval([Sum|Rest],
and so on... testing:
R = .
of course, the 'catchall' eval(Result, Result). must be the last
|Beginner Prolog. Using lists and recursion. (connecting lists together)|
You need to use the head of each rule to specify when it applies. For
|Replacing white spaces in prolog|
There are may ways in which this can be done. I find the following
particularly simple, using atomic_list_concat/3:
?- atomic_list_concat(Words, ' ', 'How are you today?'),
atomic_list_concat(Words, '_', Result).
Words = ['How', are, you, 'today?'],
Result = 'How_are_you_today?'.
For SWI strings
The above can also be done with SWI strings. Unfortunately, there is
|Unsure of why code snippet works/what it's doing with logic riddle|
I've downloaded the code from the link you provide, to test with
SWI-Prolog: there are a couple of syntactic problems in bibmm.pl, and
at least set_equal/3 must change to:
After the correction, it does produce:
X = [[keith, fell, 5], [libby, jule, 6], [margo, grant, 2], [nora,
hall, 3], [otto, ivey, 4]] ;
X = [[kei
|Understanding Difference Lists|
Paul Brna has explained this very well. He uses variables OpenList#
and Hole# in his difference-list version of append:
difference_append(OpenList1-Hole1, Hole1-Hole2, OpenList1-Hole2).
Example of use:
?- difference_append([a,b,c|H1]-H1, [d,e,f|H2]-H2, L).
H1 = [d, e, f|H2],
L = [a, b, c, d, e, f|H2]-H2.
|Determining if graph is connected in prolog|
Solution 1: Using a library
This is easy once you use a graph theory library. I'll first rewrite
your graph using S-representation:
Then I'll use library ugraph included in SWI-Prolog (thanks to Richard
O'Keefe and Vitor Santos Costa):
?- G = [1-,2-[1,3],3-,4-,5-], vertices(G, Vs), member(V,
Vs), reachable(V, G, Ws)
|Prolog, Determine if graph is acyclic|
:- meta_predicate acyclic(2).
:- meta_predicate cyclic(2).
cyclic/1 succeeds if the following exists:
an acyclic connexion from X0 to X, thus:
closure0(R_2, X0,X) or more verbosely:
call(R_2, X0,X1), call(R_2, X1,X2), call(R_2,
|Strange warning and computation result in constraint logic program|
the warning is due to the fact that Coffe and Risotto are unbound when
the negation is executed. If you replace + David = Coffee, by David =
Coffee, you will avoid the warning, but the solution cannot will not
be computed. Should be clear indeed that since Coffee is unbound,
David = Coffee will always fail. You can use dif/2, the solution will
work and will be more efficient. I've named solution1/
|Execute a fact if the variable of previous fact has no result|
I don't really get if that's the only isolaxt clause you have or if
you included it to exemplify.
Anyway, if isolaxt fails then simplify_exp will fail without reaching
Is that the behavior you expect? Perhaps you meant to use ; like so:
This means either isolaxt will succeed
|Not fixed arity for a functor (Prolog)|
It is very uncommon in Prolog to use the same structure with varying
arities. To show you one such place where they could have been used
but are not, consider directives as they are used to declare a
predicate dynamic, multifile, or discontiguous. Say, I want to declare
a/2 and b/5 dynamic. The following options are possible in ISO-Prolog:
|Getting the head and tail of a list|
It is not more than that. Maybe you want to add cases for empty lists:
compose(, , ).
compose([X|_], , [X]).
compose(, [X|_], [X]).
|Undefined procedure error in prolog SWI|
SWI has a slightly different top level shell much inspired by Prolog
IV's shell. The idea is that you get back as an answer again an
executable query. Therefore true. instead of yes and false. instead
of no. This is particularly useful if you want to "paste back" an
answer into the next query.
Xs = ,
Ys = [1, 4, 7] ;
Xs = ,
Ys = [4, 7] ;
Xs = [1, 4],
Ys =  ;
|Definition of Reflexive Transitive Closure|
It's useful, but in my opinion not yet ideal because I cannot cut
duplicate paths at the point of their creation.
Consider, with the complete graph K_n:
n_complete(N, Es) :-
numlist(1, N, Ns),
adjacent(Edges, X, Y) :- member(edge(X, Y), Edges).
pairs() --> .
pairs([N|Ns]) --> edges(Ns, N), pairs(Ns).
edges(, _) --> .
edges([N|Ns], X) --> [edg
|Check list of items and requirements in prolog|
You probably assume that there is a relation to describe dependencies
between items. Below uses
closure0/3 and non_member/2.
items_missing(Items, Needed) :-
closure0(item_needs, Item, Needed),
Missing = a ;
Missing = a2 ;
To get thi
|Prolog program: another way to define a functor|
You can use instead the standard if-then-else control construct:
double([N|L], [M|D]) :-
( even(N) ->
M is 2*N
; M is N
A performance advantage of this alternative solution (besides avoiding
repeating computations when an integer is not odd) is that, assuming
your Prolog system implements first-argument indexing (as most do),
|Multiply Two Polynomials in Prolog|
poly_sum(Ms,,Ms) :- Ms = [_|_].
poly_sum([M|Ms], [N|Ns], [S|Ss]) :-
S is M+N,
poly_sum(Ms, Ns, Ss).
scal_prod([M|Ms], Sc, [P|Ps]) :-
P is M*Sc,
scal_prod(Ms, Sc, Ps).
poly_prod(Ms,[N|Ns], Xs2) :-
scal_prod(Ms, N, Ps),
poly_sum(Ps, [0.0|Xs1], Xs2).
|How the recursiving work in prolog for adding number|
You have to change both your base case and your recursive clause:
num_between(X, X, [X]).
num_between(X, Y, [X|L]):-
X < Y,
num_between(New, Y, L).
First clause is the base case, it states that the number ranging from
X and X is just [X].
The recursive clause states that a number X which is less than a
number Y should have it in the output list (thus the [X|L] in the
|Why do we use '!' in prolog|
Beginners tend to use !/0 because they are not aware of its negative
This is because most Prolog textbooks that are popular among beginners
are quite bad and often contain wrong and misleading information about
There is an excellent answer by @false on when to use !/0. In summary:
Instead, focus on a declarative description about what holds, and try
to make the descrip
|Number of occurrences of X in the List L in prolog|
The problem is
N1 is N1+1
Variables cannot be "overwritten" in Prolog. You need to just a new
N2 is N1+1, occ1(K,L1,N2,N)
To your question "Can we replace a particular list element. If yes,
what is the syntax?":
You can only build a new list:
replace(_, _, , ).
replace(Old, New, [H0|T0], [H1|T1]) :-
(H0 = Old -> H1 = New; H1 = H0),
replace(Old, New, T0, T1).
|Prolog - alternative conslusions to a relation|
You just add said(villager,X) :- true(X) as a new fact; you don't need
to modify the original facts (as they are still true). Then you can
add said(villager,X) :- false(X). Which all amounts to what you
This seems to match "villager sometimes tells the truth, sometimes
doesn't"? It seems like you have no basis, based on the truth of a
statement, to tell if the villager said it;
|Create some default facts from another fact to be able to retract some instances|
The quick answer is:
?- forall(a(X), assert(b(X)))
However, notice that b/1 must be declared to be a dynamic predicate
(i.e., a predicate whose clauses can be asserted/retracted at
run-time). This is declared in the following way:
|Board Assembly with constraints|
Trivial with CLP(FD):
Board = [[A1,A2,A3],
maplist(top_bottom, [A1,A2,A3], [B1,B2,B3]),
maplist(top_bottom, [B1,B2,B3], [C1,C2,C3]),
maplist(left_right, [A1,B1,C1], [A2,B2,C2]),
maplist(left_right, [A2,B2,C2], [A3,B3,C3]),
|Counter resets after predicate call|
You are 'reversing' the computation flow. Try
checkStacks([Head|Tail], Counter1, Counter2) :-
checkStacks(Tail, StackCounter1, StackCounter2),
Symbol = Head,
((Symbol = 's1'; Symbol = 'S1') -> Counter1 is
StackCounter1 + 1; Counter1 is StackCounter1),
((Symbol = 's2'; Symbol = 'S2') -> Counter2 is
StackCounter2 + 1; Counter2 is StackCou
|How to check if the paths are connected between rooms|
Try something like
connect(Bgn,End,Path) :- % to find a path between two nodes in the
connected(Bgn,End,,P) , % - we invoke the helper, seeding the
visited list as the empty list
reverse(P,Path) % - on success, since the path built has
stack semantics, we need to reverse it, unifying it with the result
connected(X,Y,V,[X,Y|V]) :- % can we get directly from X to Y?
|Card battle in prolog|
I resolved my problem. This is my solution. It is implementation of
card war game. According to this wiki url:
war(,):-write(' no results, all winners!!!'),!,fail.
war(X,):-write(' First player won! '),displayKards(X),!,fail.
war(,Y):-write(' Second player won! '),displayKards(Y),!,fail.
|Limiting variable scope in prolog|
You can do it like this:
First, create the desired list structure, with different variables:
?- maplist(length, Lists, [2,3,4]).
Lists = [[X1, X2], [X3, X4, X5], [X6, X7, X8, X9]].
Then, using the following additional definition:
same_element(Ls) :- maplist(=([_]), Ls).
you can unify variables that are in the same sublist to the same term:
?- maplist(same_element, [[X1, X2], [X3, X4, X5],
|Prolog infinite loop issue|
The central misunderstanding here is what termination means in Prolog.
That is, universal termination. The query of interest is the
R = [ (2, 2)]
Prolog's top-level shell offers you first a single answer. But you get
more of them by entering ; or SPACE. So Prolog was not finished when
showing you the first answer/solution. In fact:
R = [
|Prolog find all subsets matching condition|
Provided scoreSum/2 starts with scoreSum([H|T], Tot) :- ...
seq_subseq([_|Es], Fs) :-
seq_subseq([E|Es], [E|Fs]) :-
?- setof(S, possiblesubset(S), Subs).
?- setof(S, (suitables(L), seq_subseq(L,S), cond(S)), Subs). % No L^
needed ; there is only one L.
|Bertrand Russell Puzzle|
Direct translation of the problem statement to ECLiPSe Prolog with
ic_symbolic constraint programming library:
:- local domain(symbol(w,x,y,z)).
russel(A, B, C, D) :-
[A, B, C, D] &:: symbol,
(A &= x) => (C &= y),
(B &= y or B &= z) => (A &= x),
(C &= w) => (B &= z),
(D &= y) => (B &= x),
|Cut(!) vs return|
There is no direct correspondence of Prolog's execution mechanism and
those of traditional imperative languages. So any analogy rather leads
you on a dead path.
In your example, the cut has no effect whatsoever: The (->)/2 alone
will already exclude the Else branch. In a sense it does a "tiny" cut
on If and the alternative. Would there be another clause to pred/1,
your cut would exclude that b
|Family database prolog query|
This is a very odd database layout, but that doesn't need to stop us.
First the head of the rule with the things we're going to return:
q(MotherFirst, MotherLast, UnemployedKids, CombinedIncome) :-
We're considering families here, so let's match them and pull out the
family(_, person(MotherFirst, MotherLast, _, _), Children),
The underscores there correspond to the father,
|Journey through Labyrinth 20x20 with 2 enters and 2 exits|
It's not exactly clear how your model works. For instance,
what is east/2?
what is entrance1/2 or entrance2/2?
what is exit1/2 or exit2/2?
However, your model seems to define the maze as a grid with certain
cells marked as walls, entrances or exits. Further, you seem to define
things in negative terms, rather than defining the connections between
But either way, finding a path thro
|Get list of two numbers that add up to a number in prolog|
Using between as you suggested:
getNumbers(M, C, S):-
between(0, S, M),
C is S - M.
and to get the full list you would use findall/3, e.g. this query:
?- findall([M,C], getNumbers(M, C, 5), Numbers).
Numbers = [[0, 5], [1, 4], [2, 3], [3, 2], [4, 1], [5, 0]].
|Implement counter prolog|
You cannot change the value of a variable that has been already bound.
You need to use a new variable, for example, I1 is I + 1, or maybe
Another thing you can do if you want to anyway use the side effect
(printing in your case), is to put between in a forall loop:
?- forall(between(0, 4, X), format('~d~n', [X])).
You can of course have nested foralls:
|Add number to each element in a list|
I like the idea of mutual recursion between istree/1 and isforest/1.
If you want to enforce the property you probably want code like this:
(number(H) ; istree(H)),
No mutual recursion here though.
Your istree/1/istree/2 code is pretty wide of the mark. I wouldn't
worry so much about these two clauses except you indicated to
@PauloMoura that you t
|Prolog to Conjunctive Normal Form|
The question "You want to query the database with r. What clause,
should you add to your database?" refers to so called refutation
proofs. In a refutation proof one does not proof:
Database |- Query
Instead one proofs:
Database, ~Query |- f
In classical logic the two are the same. So in your example you would
need to show that p ^ q ^ (r V ~q) ^ (~p V ~s) ^ (s V ~t) ^ t ^ ~r
leads to a con