In prolog there is no concept of functions like you are trying to do in your code. You should do: random(N), assert(fact(N)) I recommend reading at least first two chapters Learn Prolog Now! to better understand search and unification....
You need an extra argument for the list. So you cannot call it check/1 having a single argument, but — let's say — related_to/2. related_to(X, Ys) :- setof(Y, fact(X, Y), Ys). Sample queries: ?- related_to(a, Xs). Xs = [b, d]. ?- related_to(b, Xs). Xs = [c]. ?- related_to(d, Xs). false....
If you do experiments as a beginner, better stick to using the prolog-toplevel. In this manner you can rapidily identify the problem. Since you are most probably using SWI7 - like so: ?- append("hello ", B, FinalString), append(A, "world", FinalString), append(A, B, FinalString). false. So if this is false, lets...
Define: criteria(R,[_,_,N1],[_,_,N2]) :- compare(R,N2,N1). and use "predsort/3" like in: ?- predsort(criteria,[ [Joe, Pilot, 100], [Stan, Co-Pilot, 300], [Steve, Pilot, 150] ], Xs). Xs = [[Stan, Co-Pilot, 300], [Steve, Pilot, 150], [Joe, Pilot, 100]]. If duplicated third elements can exists, "criteria" must be changed. By example as: criteria(R,[_,_,N1],[_,_,N2]) :- N1=\=N2, !,...
It is a non-provable operator. See this link to learn more. Basically, it's true if the argument is not provable.
The input format of your problem is not clear. If you have one predicate for each flight-pilot pair, this will do: % flight(ID, PILOT) flight(1, 100). flight(1, 102). flight(2, 100). flight(2, 103). flight(3, 102). flight(3, 103). flight(3, 104). :- ID=3, % flight id findall(pilot(PILOT), flight(ID, PILOT), Xs), % find all...
The cut in above examples has the following effect: Ideally, it commits the search which might happen within solve_task_a/6 to the first answer found. This frees resources for finding further answers which improves space consumption. Scope problems However, at the same time, it might also hide further answers to agent_current_position/2....
My Prolog is slightly rusty, but I believe that this should do it: node(Left, Right). trav(node(Left, Right), L) :- trav(Left, L1), trav(Right, L2), append(L1, L2, L). trav(X, [X]) :- X \= node(A, B). Intuitively, trav(Left, L1) says traverse the left subtree, storing each element in L1. trav(Right, L2) says traverse...
The correct first clause of your predicate is a combination of the two clauses you have on top now. First one insists the K is 0: you don't want this. Second one insists on having one extra variable at the end of the second list: you don't want this either....
The first clause should be: fill(0, _, []). Your code leaves a choice-point (for your sample query): when the counter reaches zero, both clause heads unify with the current goal. Only by trying to use the second clause, will the N1 >= 0 goal be reached. This goal will fail...
This implements consecutive in the sense you gave in the comments. For a list of N values, we need space enough to make all the values fit in between, and all values need to be different. consecutive([]). % debatable case consecutive(Xs) :- Xs = [_|_], length(Xs, N), all_different(Xs), max_of(Max, Xs),...
algorithm,variables,recursion,prolog,logic
Check if the Prolog implementation that you are using supports clpfd! :- use_module(library(clpfd)). The implementation of toN/2 gets declarative and super-concise: toN(N,A) :- A #>= 0, A #< N, labeling([up],[A]). You'll find more labeling options in the clpfd manual: SWI-Prolog clpfd, SICStus Prolog clpfd....
As I understand it, you want a predicate that evaluates this function: In a procedural language, you'd write something like this iterative solution: static double iterative_harmonic_number( int n ) { if ( n < 1 ) throw new ArgumentOutOfRangeException("n"); double r = 0.0 ; while ( n > 0 )...
Generally, you do not iterate in Prolog. Instead, you write a rule with a pair of recursive clauses, like this: dosomething([]). dosomething([H|T]) :- process(H), dosomething(T). The first clause processes the base case, when the list [] is empty. In this case, there is nothing to do, so the body of...
string,split,prolog,swi-prolog,punctuation
"split_string" is not standard but, in the implementation I know, you can not. From the ECLIPSe manual: The string String is split at the separators, and any padding characters around the resulting sub-strings are removed. Neither the separators nor the padding characters occur in SubStrings. http://www.cs.uni-potsdam.de/wv/lehre/Material/Prolog/Eclipse-Doc/bips/kernel/stratom/split_string-4.html ** Addendum ** We...
I would rather see this as two separate problems: First, get derivation right (you're probably getting close, depending on your concrete requirements). Then, work on simplifying expressions on an algebraic level. Exploit algebraic identities, see if applying the laws of commutativity / associativity / distributivity on some subexpressions enable their...
The comment by @false is correct, as far as I can see: given two sets S and S': if S is a subset of S', then the intersection of the complement of S' and S should be the empty set (there are no elements outside of S' that are elements...
keep it simple: edge(X, Y) :- face(_, A, B, C), (X=A,Y=B ; X=B,Y=C ; X=C,Y=A). and you'll get ?- bidirEdge(X,Y). X = v2, Y = v0 ; X = v0, Y = v2 ; false. the solution order doesn't match the requirement. Should be simple to change as required......
Well,First take a look on this question executing operation for each list element in swi-prolog and others to know how to do for-each operation on lists. Second, here is the code: prod(X,[],[]). prod(X,[HEAD|TAIL],L) :- prod(X,TAIL,L1), W is X * HEAD, L = [W|L1]. prod2([],Y,[]). prod2([HEAD|TAIL],Y,L) :- prod(HEAD,Y,L1), prod2(TAIL,Y,L2), append(L1,L2,L). output:...
This topic is known as coroutining, and to be solved in fairly general way - afaik - requires extension to the basic Prolog computation model. Fortunately, most Prologs have such extension... So, let's try in SWISH to build your own 'reactive' extension: my_succ(X, Y) :- when((nonvar(X);nonvar(Y)), succ(X, Y)). edit not...
some problems: hasvitamin(L):- hasvitaminD(x), % x must be uppercase for it to be a Variable addto(X,L,L), % will never succeed, since Prolog variable are *immutable* hasvitamin(L). % recursing with the same input would lead to infinite loop from your problem description, I think you should learn about all solutions builtins....
The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, all in the form of the one you posted. SPOILER ALERT: the following links contain prolog solutions to the puzzle Here is a solution using ic (constraint solver) library: https://gist.github.com/JuanitoFatas/2227711...
oauth,google-api,prolog,swi-prolog
Okay finally worked this step out. If anyone is interested: Using status_code(_ErrorCode) seemed to resolve the problem with streampair and I needed to set redirect_uri='postmessage' for the request to work. I also used http_open rather than http_post. :- use_module(library(http/thread_httpd)). :- use_module(library(http/http_dispatch)). :- use_module(library(http/http_error)). :- use_module(library(http/html_write)). :- use_module(library(http/http_session)). :- use_module(library(http/js_write)). :-...
If you use the cumulatives/[2,3] constraint instead of the cumulative/1 constraint, then you will get the assigned machine for 'free'. By use of cumulatives each single machine can be given individual resource capacity. This shows your problem solved by use of cumulatives: :- use_module(library(clpfd)). :- use_module(library(lists)). go( Ss, Es, Ms)...
X=Y+1 tries to unify variable X with term Y+1. As you are passing 7 and 6 to your procedure, it tries to unify 7 with the term 6+1 which are not equal. What you want is to evaluate the right side of the expression (Y+1) and see if it equals...
With dif/2 you can explicitly state that for any member X preceding Element, X \== Element: prefix(Element, [Element|_], []). prefix(Element, [Head|List], [Head|Prefix]) :- dif(Element, Head), prefix(Element, List, Prefix). or equally, because I wanted to use append/3 in the first iteration of my answer: prefix(Element, List, Prefix) :- append(Prefix, [Element|_Suffix], List),...
If L is a term, you can replace: %append(L,List,List_New), with: List_New=[L|List], ...
Right now you're naming the people's jobs, solution:- List = [father("Baker" , BakerFatherJob), father("Carpenter" , CarpenterFatherJob), father("Miller" , MillerFatherJob), father("Farmer", FarmerFatherJob)], List2 = [son("Baker" , BakerSonJob), son("Carpenter" , CarpenterSonJob), son("Miller" , MillerSonJob), son("Farmer", FarmerSonJob)], Amend your code to also name the jobs' persons: member( father( OlderBakerName, "Baker"), List), member( father(...
They are not the same: Anew is + (A is H1 * H2), % ^^ ^^ bad! instead, write (given standard operators): Anew is A + H1 * H2, ...
, has a lower precedence value than ;. What this means in Prolog, is that an expression like X ; Y , Z is interpreted as X ; (Y , Z) To group them the other way around, you have to use parenthesis: (X ; Y) , Z ...
OK, this is a complex issue. You assume it is a trick question, but is it really one? How can we be sure? I will let library(clpfd) do the thinking for me. First I will rewrite your program: :- use_module(library(clpfd)). fx([],0). fx([H|T],S):- fx(T,S1), S1 #> 2, S #= S1 +...
Most likely you are looking for when/2. It is offered by both SICStus Prolog (manual page) and SWI-Prolog (manual page). Sample use: myfreeze1(V,Goal) :- when(nonvar(V),Goal). myfreeze2(V1,V2,Goal) :- when((nonvar(V1);nonvar(V2)),Goal). ...
write('\33\[1mbold\33\[0m'). That is, octal escape sequences (and hexadecimal which start with \x) need to be closed with a \ too. En revanche, a leading zero is not required, but possible. This is in no way specific to GNU, in fact, probably all systems close to ISO Prolog have it....
Using tfilter/3: positive_truth(N, true) :- N >= 0. positive_truth(N, false) :- N < 0. ?- tfilter(positive_truth, [-1,2,3,-5,-7,9],Result). Result = [2,3,9] Alternatively, using library(clpfd): pos_truth(Expr, Truth) :- Expr #>= 0 #<==> Bool, bool01_truth(Bool, Truth). bool01_truth(0,false). bool01_truth(1,true). ?- tfilter(pos_truth, [-1,2,3,-5,-7,9],Result). Result = [2,3,9]. ?- tfilter(pos_truth, [X,Y],Result). Result = [], X in inf.....
Your list is for all intents and purposes a base-100 number. The easy way to solve it is to do the arithmetic in the same way in which you would evaluate it long hand: start with the least significant digit, working to the most significant digit, sum each pair of...
Try: lemmas:- odbc_query('my_db', 'SELECT * ,case \ when ActualCost<EstimatedCost then \'true\' \ else \'false\' \ end as Value \ from Work_Order ' ). ...
It doesn't work all at once, but bit by bit. As if defined by the following two clauses: repeat. repeat :- repeat. ...
Once we "reach" the fact(1,1), it will "return" to the calling recursive iteration and proceed to the part R is R1*X of that iteration, with R1=1. Then will return again to a previous level and so on. Let's look at a non-trivial iteration: fact(3,R) : X <- 3, X1 <-...
_ alone is an anonymous variable. Multiple occurrences in the same clause (or the same read-term) represent different variables. A variable starting with _ but containing further characters is not an anonymous variable. Several occurrences represent the same variable. By convention, many Prolog systems require that variables occurring only once...
The reason is: the second claused is used even if N=0. This leads to a chain of calls fill(0,...) => fill(-1,....) => fill(-2, ....) => .... Remedy: Adding a cut to the first clause should avoid this....
First, we define an auxiliary predicate list_taken_rest/3: list_taken_rest([], [], []). list_taken_rest([X|Xs],[X|Ys], Zs ) :- list_taken_rest(Xs,Ys,Zs). list_taken_rest([X|Xs], Ys ,[X|Zs]) :- list_taken_rest(Xs,Ys,Zs). Let's look at a query of list_taken_rest/3 with the first argument being the list [a,b,c]. As answers we get alternative ways of parting the element of [a,b,c] between Xs and...
algorithm,prolog,unification,iso-prolog
Third attempt. This is mainly a bugfix in a previous answer (which already had many modifications). Edit: 06/04/2015 When creating a more general term I was leaving both subterms as-is if either of them was a variable. Now I build a more general term for the "other" subterm in this...
You need to say prompt(_, '') somewhere in your program before you start reading and writing to standard streams. From the entry for prompt/2: A prompt is printed if one of the read predicates is called and the cursor is at the left margin. It is also printed whenever a...
maybe, using another casual predicate instead of main/0... ?- with_output_to(atom(X), listing(pattern)), write(X). gram:pattern(A, B, C) :- dig(A, B, C). gram:pattern(A+C, B, E) :- ten(A, B, D), dig(C, D, E). ... ...
Paulo explained well what the problem is (+1). Maybe you should correct your code like predicate(L1, Restriction) :- maplist(=(1), L1), Restriction. that yields the expected output ?- predicate([A,B,C], A==1). A = B, B = C, C = 1. ...
a) You have a dot that must be comma in: collision(X,Y):- member(X,GroupA),member(Y,GroupA). member(X,GroupB),member(Y,GroupB). b) Better you do not redefine "member", it is standard. c) If I change dot by comma in: collision(X,Y):- GroupA(L),member(X,L),member(Y,L), GroupB(L),member(X,L),member(Y,L). this statement will fail always because there are no list "L" common to GroupA and GroupB....
Is there a way? Of course: -Pick 2 members of the original list, place them in T1. -Pick 3 members in the rest and place them in T2. -The rest is T3: teams(L, T1, T2, T3) :- pick2(L, T1, L1), pick3(L1, T2, T3). pick2(L, [M1, M2], Rest) :- member(M1, L),...
Typically, after first answer is written, you can type some key, usually ";", to backtrack and receive another answer.
module,prolog,standards,iso,iso-prolog
The system you cite, SWI-Prolog, is a system whose core is developed by a single developer. Such bold statements as those you quote are his very personal opinions. In the past, SWI did follow ISO standards for a certain period. Then, recently changed. If you want to read more about...
You will need to use the foreign language interface of your Prolog system to call an external API that does the speech synthesis. Prolog foreign language interface are not standard but Prolog system specific. Thus, without further details, is not difficult to give you more specific advise. UPDATE: An alternative...
Yes, of course, there is a solution. You are getting a list of results so you need to filter them by specific predicate or just take last one because you sort them in increasing order. Prolog generates these solutions one by one. Sometimes we would like to have all the...
You asked: So how can I solve this? The following is a general methodology, that always works for pure, monotonic Prolog programs like yours. Your actual problem is that a specific goal should succeed, but it fails. So you got an unexpected failure. To localize the responsible part of your...
Prolog doesn't have tuples, since we can implement them as a recursive application of comma operator. For general processing, read the section about analysing terms. In particular, (=..)/2 it's often used to perform arguments processing of a structure, but what you need here could be conj_list((A,B), [A|Bs]) :- conj_list(B, Bs),...
Usually, one would not define a proper predicate for this, but rather use maplist/2 for the purpose: ..., maplist(=(0), Zs), ... To give a concrete example: ?- Zs =[A,B,C], maplist(=(0), Zs). This query corresponds to: ?- Zs = [A,B,C], call(=(0), A), call(=(0), B), call(=(0), C). or even simpler: ?- Zs...
Determinstic variant First a more efficient but deterministic approach: occurs_most([],_,0). occurs_most(List,X,Nr) :- msort(List,[H|T]), most_sort(T,H,1,H,1,X,Nr). most_sort([Hb|T],Ha,Na,Hb,Nb,Hr,Nr) :- !, Nb1 is Nb+1, most_sort(T,Ha,Na,Hb,Nb1,Hr,Nr). most_sort([Hc|T],_,Na,Hb,Nb,Hr,Nr) :- Nb > Na, !, most_sort(T,Hb,Nb,Hc,1,Hr,Nr). most_sort([Hc|T],Ha,Na,_,_,Hr,Nr) :- most_sort(T,Ha,Na,Hc,1,Hr,Nr). most_sort([],Ha,Na,_,Nb,Ha,Na) :- Na >= Nb, !. most_sort([],_,_,Hb,Nb,Hb,Nb). First you use msort/2 to sort the list. Then you iterate over...
Just as stated in the article: "The child of one's second cousin". secondCousinOnceRemoved(H, G) :- child(H, F), secondcousin(F, G). ...
Use is/2 to force the arithmetic evaluation. On their own, Prolog terms are just structural symbolic entities, X-2 is a compound term of arity 2, -(X,2): 3 ?- write_canonical( X-2 ). -(_,2) true. But is is for arithmetic expressions: 4 ?- Z is 5-2. Z = 3. Your definition should...
TL;DR: Prolog is right. And you really are doing the best taking the messages seriously. You are using if-then-else in an unconventional manner. For this reason it is not that simple to figure out what is happening. When I say listing(check) I get the following: check(A, B) :- ( related_to(A,...
@gusbro's answer (s(X)) shows you how you somewhat solve this with GNU's debugger. However, if you cannot afford to see all the printing going on, or it is much too slow, you might consider the following "debugger". I personally do not use debuggers offered by Prolog systems for the simple...
ISO/IEC 13211-1 has several requirements for integers, but a concrete representation is not required. If the integer representation is bounded, one of the following conditions holds 7.1.2 Integer ... minint = -(*minint) minint = -(maxint+1) Further, the evaluable functors listed in 9.4 Bitwise functors, that is (>>)/2, (<<)/2, (/\)/2, (\/)/2,...
To understand what happens, you must see Prolog as a theorem solver: when you give Prolog the query ?- copyList([1, 2, 3], L)., you're essentially asking Prolog to prove that copyList([1, 2, 3], L) is true. Prolog will therefore try to prove it. At its disposal, it has two clauses:...
You can use findall followed by sort to collect unique results of a query (you don't want duplicate invoices in your list), and length to check the length of the collected results. For example: findall(X, (invoice(X, C, P, _), customer(C, _, f, _), cleanProd(P)), Xs), sort(Xs, InvoicesOfWomenBuyingCleanProducts), length(InvoicesOfMenBuyingCleanProducts, N). Also,...
prolog,primes,sieve-of-eratosthenes,prolog-coroutining
Ok i found out solution i had to change recursive call in sieve so now i call it in freeze predicate. as requested i found clue here Lazy lists in Prolog? sieve(N,L) :- sieve(L,Strumien,[]), numlist(2,N,X), X = Strumien. sieve(L,Strumien,X) :- freeze(Strumien, ( Strumien =[H|T], filter(H,T,Z), sieve(L,Z,[H|X]) )). sieve(L,[],L). filter(H,S,X) :-...
You need to use the vertical bar [Top|Rest] syntax twice in order to pull out an element from the nested list, like this: testfunction([[Top|_]|_]):- write(Top),nl,nl. Now Top unifies with the first element of the first list in a list of lists. Note that you do not have to use unification...
In Prolog, you cannot reassign variables. So expressions such as R is R // 2 will fail since, in Prolog, it semantically says that *R is itself integer divide by 2 which would only be true if R was 0. Likewise, given that a Tape is a list, you cannot...
You want to describe a sequence of elements. For such, there is a special formalism in Prolog called Definite Clause Grammars. Before using the formalism, let's try to figure out how a sequence with E occurring exactly twice looks like: First, is a possibly empty sequence which does not contain...
You keep track of what nodes in your graph that you've already visited. You need to do this anyway, as you need to detect cycles in your graph lest you fall into the rabbit hole of infinite recursion. And in Prolog, we use helper methods that carry state around as...
Prolog is a declarative language, you must state correctly your patterns: size(node(L,R), Size) :- ... % why you add 1 to left+right sizes ? From the samples, I suggest to stop the recursion with Size = 1 when anything that is not a node is seen: size(node(L,R), Size) :- !,...
Solved using another approach. Code is attached (algorithm is in the code). Some predicates from prev. case remained though (like try_bind). Code at http://pastebin.com/0Eb7qUjS or: % Author: Denis Korekov % Description of algorithm: % G1 is graph 1, G2 is graph 2 % E1 is edge of G1, E2 is...
The error is very likely because in your code: listtrans([H|T],L1):- trans(H,B), append(B,L,L2), listtrans(T,L2). the variable L1 is declared in the head, but not referenced anywhere: you mispelled something? Anyway, your code is not going to work. Moreover, using append/3 for this kind of tasks which are easily defined by recursion...
The predicate nth0/3 is not part of ISO Prolog, so there is no explicit reference. However, the way how and when errors are reported is defined in the standard. In particular, type errors are never reported due to an argument being not sufficiently instantiated. The concrete formulation in the SWI...
The answer by CapelliC is perfect. Just to explain: When you have a Prolog clause like this: foo([H|T], [H|Z]) :- foo(T, Z). which you then call like this: ?- foo([a,b,c], L). from: foo([H| T ], [H|Z]) with H = a, T = [b,c], L = [a|Z] call: foo([a|[b,c]], [a|Z]) which...
It's possible there are other problems, but reverse([], ReversedList). is almost surely not what you want here. The reverse of an empty list is an empty list, translates to reverse([], []). Additionally, reverse([A,B], ReversedList) is also probably not what you want. It is not a list with head A and...
module,prolog,predicate,swi-prolog,built-in
You can query the properties of a predicate using the standard predicate_property/2 predicate. In this case we get: ?- predicate_property(term_string(_,_,_), P). P = interpreted ; P = visible ; P = built_in ; P = static ; P = imported_from('$syspreds') ; P = file('/Users/pmoura/lib/swipl-7.3.1/boot/syspred.pl') ; P = line_count(1196) ; P...
python,text,prolog,text-to-speech,swi-prolog
One option is to use shell/2 From http://www.swi-prolog.org/pldoc/man?predicate=shell/2 ?- shell('cmd.exe /C copy file1.txt file2.txt'). Then your python script should be called as usual from shell ?- shell('cmd.exe /C python hello.py > out.txt'). ...
Let's say you have unified the parameter number 4 with variable B_list. If you would like to take the list from inside it, use unification operator =, like this: /* Let's pretend that you do not need other parameters */ plane(_, _, _, B_list, _) :- /* This assigns the...
Maybe this helps: checkCap :- ves(X,Y,Z), % look up dynamic database write(ves(X,Y,Z)), % write out term nl. ...
This is extremely easy to solve with CLP(FD) constraints. To your first question (why does this fail): is/2 does not work with compound terms on its left hand side. You need =:=/2 to compare the evaluation of arithmetic expressions. Still, simply replacing is/2 with =:=/2 does not work in your...
Seems fine to me... What's the problem? $ swipl Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.1.37) Copyright (c) 1990-2015 University of Amsterdam, VU Amsterdam SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. Please visit http://www.swi-prolog.org for details....
prolog,artificial-intelligence,expert-system
It works, at least in SWI-Prolog version 6.6.6. Let's have both rules defined: rule((fix(Advice) :- (bad_component(X), fix(X, Advice))), 100). rule((fix(Advice) :- (bad_component(X); fix(X, Advice))), 100). If we ask for available rules we obtain both of them: ?- rule((A :- B), C). A = fix(_G2329), B = (bad_component(_G2334), fix(_G2334, _G2329)), C...
+1 for using CLP(FD) constraints for this task! forall/2 and constraints do not mix very well, since backtracking revokes posted constraints. Your example works as expected with: flip_init(Prop, D) :- clpfd:init_propagator(D, Prop). and using maplist(flip_init(Prop), Ds) instead of forall/2. The next problem is then that digits_to_nonneg([1,2], N) simply fails, but...
maplist(P_1, Xs) will call call(P_1, X) for each element of Xs. The built-in predicate call/2 adds one further argument to P_1 and then calls this with call/1. To indicate that a further argument is needed, it is very helpful to use a name like P_1 meaning "one extra argument is...
Quick fix: Use format/2 instead of write/1! For more information on the built-in predicate format/2, click here. $ swipl --traditional Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.1.37) [...] ?- write("abc"). [97,98,99] % output by write/1 via side-effect true. % truth value of query (success) ?- format('~s',["abc"]). abc % output...
To find the number of all children of a specific person, you need to collect all solutions to father(Father, Children) or mother(Mother, Children) and count them. For example: number_of_childrens(Person, N) :- findall(Children, (father(Person, Children); mother(Person, Children)), Childrens), length(Childrens, N). For example: ?- number_of_childrens(joe, N). N = 3. ...
You could use flatten/2 and atomic_list_concat/3: :- X = [[[[a]|fat]|man],[[[[[was]|walking]|quickly],to],[[[[the]]|end],[of,[[[the]|long]|corridor]]]]], flatten(X,Y), atomic_list_concat(Y,' ',Z). X = [[[[a]|fat]|man], [[[[[was]|walking]|quickly], to], [[[[the]]|end], [of, [[...|...]|...]]]]], Y = [a, fat, man, was, walking, quickly, to, the, end|...], Z = 'a fat man was walking quickly to the end of the long corridor'. ...
Use unification: ?- List = [a=3, b=2, c=0], member(Left=Right, List). List = [a=3, b=2, c=0], Left = a, Right = 3 ; List = [a=3, b=2, c=0], Left = b, Right = 2 ; List = [a=3, b=2, c=0], Left = c, Right = 0. Here, something like a=3 is...
First of all, there is a builtin nth0/3 for that: ?- nth0(0,[a,b,c],X). X = a. ?- nth0(1,[a,b,c],X). X = b. ?- nth0(2,[a,b,c],X). X = c. ?- nth0(3,[a,b,c],X). false. Get the i-th element The problem is in the inductive case: match([Elem|Tail],Num,Counter,MatchedNumber):- match(Tail,Num,N,Elem), C is N+1. Prolog doesn't know anything about C...
A simple solution using the sort/2 ISO standard built-in predicate, assuming that neither list contains duplicated elements: equal_elements(List1, List2) :- sort(List1, Sorted1), sort(List2, Sorted2), Sorted1 == Sorted2. Some sample queries: | ?- equal_elements([1,2,3],[1,2,3,4]). no | ?- equal_elements([1,2,3],[3,1,2]). yes | ?- equal_elements([a(X),a(Y),a(Z)],[a(1),a(2),a(3)]). no | ?- equal_elements([a(X),a(Y),a(Z)],[a(Z),a(X),a(Y)]). yes ...
The article seems not be very explicative. Assume the call is "sg(a,W)". Let analize first possibility: sg(X,Y) :- par(X, X1), par(Y,Y1), sg(X1,Y1) first "par" will be queried as "par(X=a,X1)", next as "par(Y=W,Y1)". This last query is a totally unbound query, and probably is what the article tries to skip. Now,...
bash,prolog,swi-prolog,logic-programming
I think this has nothing/not much to do with SWI-prolog itself, but more with the command line handler. If I place the goal between single quotes (''), it works: swipl -s consultingfile.pl -g 'start(1)' The brackets are probably wrongly interpreted by the shell. If I use your command it gives:...
Near to correct, but some small error. Line by line: a) spit([], 0, [], []). typo: spi vs split The rule says "the split of an empty list by 0 are two empty lists", true, but too restrictive, change it to "the split of empty list is two empty list,...
It depends on the operating system that you are using. For Linux see this discussion. In my opinion PDT plugin for Eclipse is pretty good.
The +, ?, -, and @ are standard predicate argument instantiation modes. They are used in the documentation of predicates to inform the user of the supported modes that can be used when calling the predicate. Their meaning, as defining in the ISO Prolog standard. are: + - the argument...