w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » PROLOG » Page 1
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

Categories : Prolog

Most general higher-order constraint describing a sequence of integers ordered with respect to a relation
Hoogle was not very useful, but Hayoo is! foldcmpl so this is a special form of fold for a list, but it does not apply length list times but one time less. isSortedBy 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

Categories : Prolog

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 true_check([_,H,B]):- call(H)->true;B=..L,true_check(L). true_check([B]) :- call(B)->true;false. possible(Rule):- current_predicate(rule,Head), clause(Head,B), B=..I, true_check(I), Head=..[_,Rule].

Categories : Prolog

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], Result). eval(Result, Result). and so on... testing: ?- eval([1,2,sum,4,sum],R). R = [7]. of course, the 'catchall' eval(Result, Result). must be the last rule...

Categories : Prolog

Beginner Prolog. Using lists and recursion. (connecting lists together)
You need to use the head of each rule to specify when it applies. For example: connectLists([],L,L). connectLists(L,[],L). connectLists([H1|T1],[H2|T2],[H1,H2|T]) :- connectLists(T1,T2,T).

Categories : Prolog

Replacing white spaces in prolog
For atoms 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 no string_list_conc

Categories : Prolog

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: set_equal([H|T],R):- member(H,R),select(H,R,Rez),set_equal(T,Rez). After the correction, it does produce: ?- start(X). X = [[keith, fell, 5], [libby, jule, 6], [margo, grant, 2], [nora, hall, 3], [otto, ivey, 4]] ; X = [[kei

Categories : Prolog

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.

Categories : Prolog

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: [1-[2],2-[1,3],3-[2],4-[5],5-[4]] Then I'll use library ugraph included in SWI-Prolog (thanks to Richard O'Keefe and Vitor Santos Costa): ?- use_module(library(ugraph)). ?- G = [1-[2],2-[1,3],3-[2],4-[5],5-[4]], vertices(G, Vs), member(V, Vs), reachable(V, G, Ws)

Categories : Prolog

Prolog, Determine if graph is acyclic
Using closure0/3: :- meta_predicate acyclic(2). :- meta_predicate cyclic(2). acyclic(R_2) :- +cyclic(R_2). cyclic(R_2) :- closure0(R_2, X0,X), call(R_2, X,X0). ?- acyclic(graph2). true. ?- acyclic(graph1). false. 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,

Categories : Prolog

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/

Categories : Prolog

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 nonvar(Y). Is that the behavior you expect? Perhaps you meant to use ; like so: simplify_exp(Term1+Term2,X,Y) :- isolaxt(Term1+Term2,Y); (simplify_exp(Term1,X,Y), simplify_exp(Term2,X,Y)). This means either isolaxt will succeed

Categories : Prolog

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: :- dynamic(a/2). :- dynamic(b/5). :- dynamic([a/2,b/5]).

Categories : Prolog

Getting the head and tail of a list
compose([X|_],[Y|_], [X,Y]). It is not more than that. Maybe you want to add cases for empty lists: compose([], [], []). compose([X|_], [], [X]). compose([], [X|_], [X]).

Categories : Prolog

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. ?- append(Xs,Ys,[1,4,7]). Xs = [], Ys = [1, 4, 7] ; Xs = [1], Ys = [4, 7] ; Xs = [1, 4], Ys = [7] ; Xs

Categories : Prolog

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), phrase(pairs(Ns), Es). adjacent(Edges, X, Y) :- member(edge(X, Y), Edges). pairs([]) --> []. pairs([N|Ns]) --> edges(Ns, N), pairs(Ns). edges([], _) --> []. edges([N|Ns], X) --> [edg

Categories : Prolog

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. item_needs(b, a). item_needs(a3, a2). item_needs(a3, a1). items_missing(Items, Needed) :- member(Item, Items), closure0(item_needs, Item, Needed), non_member(Needed, Items). ?- items_missing([b,a1,a3],Missing). Missing = a ; Missing = a2 ; false. To get thi

Categories : Prolog

Prolog program: another way to define a functor
You can use instead the standard if-then-else control construct: double([], []). double([N|L], [M|D]) :- ( even(N) -> M is 2*N ; M is N ), double(L, D). 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), the c

Categories : Prolog

Multiply Two Polynomials in Prolog
poly_sum(Ms,[],Ms) :- Ms = [_|_]. poly_sum([],Ns,Ns). poly_sum([M|Ms], [N|Ns], [S|Ss]) :- S is M+N, poly_sum(Ms, Ns, Ss). scal_prod([],_Sc,[]). scal_prod([M|Ms], Sc, [P|Ps]) :- P is M*Sc, scal_prod(Ms, Sc, Ps). poly_prod(_,[],[]). poly_prod(Ms,[N|Ns], Xs2) :- poly_prod(Ms,Ns, Xs1), scal_prod(Ms, N, Ps), poly_sum(Ps, [0.0|Xs1], Xs2). ?- poly_prod([1,2,3,4],[5,6,7],Xs). Xs

Categories : Prolog

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, increase(X, New), 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

Categories : Prolog

Why do we use '!' in prolog
Beginners tend to use !/0 because they are not aware of its negative consequences. This is because most Prolog textbooks that are popular among beginners are quite bad and often contain wrong and misleading information about !/0. There is an excellent answer by @false on when to use !/0. In summary: don't. Instead, focus on a declarative description about what holds, and try to make the descrip

Categories : Prolog

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 variable, e.g. 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).

Categories : Prolog

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 originally had. 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;

Categories : Prolog

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: :- dynamic(b/1).

Categories : Prolog

Board Assembly with constraints
Trivial with CLP(FD): :- use_module(library(clpfd)). board(Board) :- Board = [[A1,A2,A3], [B1,B2,B3], [C1,C2,C3]], 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]), pieces(Ps), maplist(board_piece(Board), Ps). top

Categories : Prolog

Counter resets after predicate call
You are 'reversing' the computation flow. Try checkStacks([],0,0). 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

Categories : Prolog

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 graph 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?

Categories : Prolog

Card battle in prolog
I resolved my problem. This is my solution. It is implementation of card war game. According to this wiki url: http://en.wikipedia.org/wiki/War_(card_game) :- use_module(library(lists)). 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. war([X1|X],[Y1|Y])

Categories : Prolog

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],

Categories : Prolog

Prolog infinite loop issue
The central misunderstanding here is what termination means in Prolog. That is, universal termination. The query of interest is the following: ?- get_all_sums(4,R). 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: ?- get_all_sums(4,R). R = [

Categories : Prolog

Prolog find all subsets matching condition
Provided scoreSum/2 starts with scoreSum([H|T], Tot) :- ... seq_subseq([], []). seq_subseq([_|Es], Fs) :- seq_subseq(Es, Fs). seq_subseq([E|Es], [E|Fs]) :- seq_subseq(Es, Fs). possiblesubset(S) :- suitables(L), seq_subseq(L, S), cond(S). ?- setof(S, possiblesubset(S), Subs). ?- setof(S, (suitables(L), seq_subseq(L,S), cond(S)), Subs). % No L^ needed ; there is only one L. How

Categories : Prolog

Bertrand Russell Puzzle
Direct translation of the problem statement to ECLiPSe Prolog with ic_symbolic constraint programming library: :- lib(ic). :- lib(ic_symbolic). :- 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),

Categories : Prolog

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

Categories : Prolog

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 mother's info: family(_, person(MotherFirst, MotherLast, _, _), Children), The underscores there correspond to the father,

Categories : Prolog

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 each cell. But either way, finding a path thro

Categories : Prolog

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]].

Categories : Prolog

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 succ(I, I1). 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])). 0 1 2 3 4 true. You can of course have nested foralls: ?- forall(b

Categories : Prolog

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: istree([]). istree([H|T]) :- (number(H) ; istree(H)), istree(T). 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

Categories : Prolog

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

Categories : Prolog




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.