This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Could you help me regarding the next three Prolog programs?
Summary of the elements in a list, and check that is divided or not divided with 3?
For example, the list is [1, 2, 3] --> and the sum of the element is divided with 3, because 1+2+3=6, and 6/3=2 --> so the output should be true.
If the 7 is in a list, doubles it. For example: the input list --> [1,7,3,7,7], the outputs should be [1,7,7,3,7,7,7,7].
If the 7 is in a list, change it for 2,7,2. For example: the input list -->[1,7,2,1], the output should be [1,2,7,2,2,1]
What is the program and how to test it with SWI-Prolog?
Thank you in anticipation!
I will give you a couple of tips:
You need a) to calculate the sum, b) check whether it divides by 3. If you use SWI-Prolog there is a predicate sum_list in the library lists that does a) and the ... is ... mod ... construction to solve b) If you need to use recursion rather than the built-in predicate to calculate the sum:
sum([X|Xs], Acc, Sum) :- Acc1 is Acc + X, sum(Xs, Acc1, Sum).
sum([], Acc, Acc).
sum(List, Sum) :- sum(List, 0, Sum).
and 3. These are recursive procedures. You should traverse the list and if 7 is encountered you should replace it with 7,7 for question 2 and with 2,7,2 for question 3.
traverse_list([],[]).
traverse_list([7|Xs], [7,7|Ps]) :-
!,
traverse_list(Xs,Ps).
traverse_list([X|Xs], [X|Ps]) :-
traverse_list(Xs,Ps).
Think about modifying this fragment for 3.
I'd recommend giving it a little thought and figuring it out on your own. That said, I'll give you something to help get started:
1) I'm assuming your instructor wants to see you do the recursion rather than use the built-in sum_list predicate. That would look something like this:
sum([FirstNum | Rest], Sum) :-
sum(Rest, Sum1),
Sum is FirstNum + Sum1.
Then use the "mod" operator to check divisibility. Remember to include a base case for when the recursion reaches the empty set []. If you can understand this, the rest should be easy. Good luck.
Related
This is probably the most trivial implementation of a function that returns the length of a list in Prolog
count([], 0).
count([_|B], T) :- count(B, U), T is U + 1.
one thing about Prolog that I still cannot wrap my head around is the flexibility of using variables as parameters.
So for example I can run count([a, b, c], 3). and get true. I can also run count([a, b], X). and get an answer X = 2.. Oddly (at least for me) is that I can also run count(X, 3). and get at least one result, which looks something like X = [_G4337877, _G4337880, _G4337883] ; before the interpreter disappears into an infinite loop. I can even run something truly "flexible" like count(X, A). and get X = [], A = 0 ; X = [_G4369400], A = 1., which is obviously incomplete but somehow really nice.
Therefore my multifaceted question. Can I somehow explain to Prolog not to look beyond first result when executing count(X, 3).? Can I somehow make Prolog generate any number of solutions for count(X, A).? Is there a limitation of what kind of solutions I can generate? What is it about this specific predicate, that prevents me from generating all solutions for all possible kinds of queries?
This is probably the most trivial implementation
Depends from viewpoint: consider
count(L,C) :- length(L,C).
Shorter and functional. And this one also works for your use case.
edit
library CLP(FD) allows for
:- use_module(library(clpfd)).
count([], 0).
count([_|B], T) :- U #>= 0, T #= U + 1, count(B, U).
?- count(X,3).
X = [_G2327, _G2498, _G2669] ;
false.
(further) answering to comments
It was clearly sarcasm
No, sorry for giving this impression. It was an attempt to give you a synthetic answer to your question. Every details of the implementation of length/2 - indeed much longer than your code - have been carefully weighted to give us a general and efficient building block.
There must be some general concept
I would call (full) Prolog such general concept. From the very start, Prolog requires us to solve computational tasks describing relations among predicate arguments. Once we have described our relations, we can query our 'knowledge database', and Prolog attempts to enumerate all answers, in a specific order.
High level concepts like unification and depth first search (backtracking) are keys in this model.
Now, I think you're looking for second order constructs like var/1, that allow us to reason about our predicates. Such constructs cannot be written in (pure) Prolog, and a growing school of thinking requires to avoid them, because are rather difficult to use. So I posted an alternative using CLP(FD), that effectively shields us in some situation. In this question specific context, it actually give us a simple and elegant solution.
I am not trying to re-implement length
Well, I'm aware of this, but since count/2 aliases length/2, why not study the reference model ? ( see source on SWI-Prolog site )
The answer you get for the query count(X,3) is actually not odd at all. You are asking which lists have a length of 3. And you get a list with 3 elements. The infinite loop appears because the variables B and U in the first goal of your recursive rule are unbound. You don't have anything before that goal that could fail. So it is always possible to follow the recursion. In the version of CapelliC you have 2 goals in the second rule before the recursion that fail if the second argument is smaller than 1. Maybe it becomes clearer if you consider this slightly altered version:
:- use_module(library(clpfd)).
count([], 0).
count([_|B], T) :-
T #> 0,
U #= T - 1,
count(B, U).
Your query
?- count(X,3).
will not match the first rule but the second one and continue recursively until the second argument is 0. At that point the first rule will match and yield the result:
X = [_A,_B,_C] ?
The head of the second rule will also match but its first goal will fail because T=0:
X = [_A,_B,_C] ? ;
no
In your above version however Prolog will try the recursive goal of the second rule because of the unbound variables B and U and hence loop infinitely.
Hey guys I'm new to prolog and learning it myself.
I found this question on the internet but without any answers.
I have this database
countries([belgium, france, germany, italy, luxembourg, netherlands]).
weight(france, 4).
weight(germany, 4).
weight(italy, 4).
weight(belgium, 2).
weight(netherlands, 2).
weight(luxembourg, 1).
threshold(12).
Now I made this program to see if a list of countries have enough votes to get over the threshold.
winning([], 0).
winning([Head | Tail], N):-
weight(Head, N1),
winning(Tail, N2),
N is N1 + N2.
winning(Y):-
winning(Y, N),
threshold(X),
N >= X.
Now I need to write a program critical/2, first argument a country, second argument a list of countries. Is the first country needed to get over the threshold or not.
example:
?- critical(netherlands, [belgium, france, germany]).
True
?- critical(netherlands, [france, germany, italy]).
False
for this program I need to check first, if the second argument is winning already. And if so it will fail. If not i need to get the value of the first argument add it to the second value and then check if its over the threshold. If it won't be enough it will fail. If it is enough it will succeed.
critical(X,Y):-
winning(Y,N),
weight(X,Value),
N1 is N+Value,
threshold(X),
N1 >= X.
I'm doing alot of things wrong here but I have no idea how to fix it.
You are quite close to the solution. A few hints:
First, a good naming convention helps you keep track of which argument is what:
critical(C, Cs) :-
This makes clear that the first argument is a single country, and the second is a list of zero or more countries.
So, let us first relate Cs to their total weight. Again, it helps to have a good naming convention, making clear which argument is what:
country_weight(france, 4).
country_weight(germany, 4).
country_weight(italy, 4).
country_weight(belgium, 2).
country_weight(netherlands, 2).
country_weight(luxembourg, 1)
Now, to relate multiple countries to their respective weights, we use the meta-predicate maplist/3:
maplist(country_weight, Cs, Ws)
and to sum the weights, we use sum_list/2:
sum_list(Ws, Sum)
It is obvious how to describe that Sum must be below the threshold (left as an exercise).
Finally, to denote that the sum plus the weight of the country denoted by the first argument is greater than the threshould, we use:
country_weight(C, W),
W + Sum > Threshold
This completes the definition. Notice that it was not necessary to describe which countries exist at all. Therefore, you can omit the first predicate of your program.
I have the following code for getting the length of a list in prolog, it works recursively.
Is there any other way for getting the length?
len([], 0).
len([H|T], N) :-
len(T, NT), N is NT + 1.
Any suggestions would be appreciated.
You are asking the wrong question :)
But seriously: the only sensible way of finding the length of a list is to use the built-in length/2. How it is implemented is irrelevant -- more important are its semantics:
?- length([a,b], 2).
true.
?- length([a,b], 4).
false.
?- length([a,b,c], Len).
Len = 3.
?- length(List, 3).
List = [_G937, _G940, _G943].
?- length(List, Len).
List = [],
Len = 0 ;
List = [_G949],
Len = 1 ;
List = [_G949, _G952],
Len = 2 . % and so on
Either way, it doesn't get simpler than that. Any other way of finding the length of a list, or checking for the length of a list, or creating a list of a certain length, or enumerating lists of increasing length is going to be less "simple" than using length/2.
And then: learning Prolog means learning how length/2, and the other nicely declarative built-ins can be used.
Repeating an element N times
Splitting a list into segments of some length
Exactly one pair in a list
Rotate a list
I am sure you can think of many other uses of length/2.
Here is an iterative solution that uses repeat/0 predicate:
getlength(L,N) :-
retractall(getlength_res(_)),
assert(getlength_res(0)),
retractall(getlength_list(_)),
assert(getlength_list(L)),
repeat,
(
getlength_list([]), !, getlength_res(N)
;
retract(getlength_res(V)), W is V + 1, assert(getlength_res(W)),
retract(getlength_list([_|T])), assert(getlength_list(T)), fail
).
This solution creates and retracts facts getlength_res/1 and getlength_list/1 as it walks through the list, replacing the old list with a shorter one, and the old number with a number that is greater by one at each iteration of repeat/0. In a sense, the two dynamically asserted/retracted facts behave very much like assignable variables of imperative languages.
Demo.
In general, iterative solutions in Prolog are harder to read than their recursive counterparts. This should come as no surprise, considering that anything that has an effect of an assignment statement of an imperative programming language goes against the grain with Prolog's design philosophy.
Sorry I could not resist to try out this "challenge":
Input=[a,b,b,b,b,b,b,b,b,a,b,c,d,f], between(1,inf,K),findall( _,between(1,K,_),FreeList), ( FreeList=Input,!,true).
findall/3 is doing the behind-the-scenes recursion, code is making unifications of lists FreeList and Input until they unify
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Here is the Question following:
For this question we consider binary expression-trees whose leaves are either of the form tree(empty, Num, empty) where Num is a number, or tree(empty, z, empty) in which case we will think of the letter z as a kind of "variable".
Every tree is either a leaf or of the form tree(L, Op, R) where L and R are the left and right subtrees, and Op is one of the arithmetic operators '+', '-', '*', '/' (signifying addition, subtraction, multiplication and division).
Write a predicate tree_eval(Value, Tree, Eval) that binds Eval to the result of evaluating the expression-tree Tree, with the variable z set equal to the specified Value. For example:
?- tree_eval(2, tree(tree(empty,z,empty),
'+',tree(tree(empty,1,empty),
'/',tree(empty,z,empty))), Eval).
Eval = 2.5 ;
false.
?- tree_eval(5, tree(tree(empty,z,empty),
'+',tree(tree(empty,1,empty),
'/',tree(empty,z,empty))), Eval).
Eval = 5.2 ;
false.
Some good ideas?
Could we achieve it without using cut(!)?
Thanks guys!
It is a shame you wouldn't even try to solve it before asking for help.
Your question almost directly translates to a solution. When there is a Num in the middle of the tree:
tree_eval(_Value, tree(empty,Num,empty), Num).
When there is a variable:
tree_eval(Value, tree(empty,z,empty), Value).
And the general case:
tree_eval(Value, tree(tree(LL,LOp,LR),Op,tree(RL,ROp,RR)), Eval) :-
tree_eval(Value, tree(LL,LOp,LR), LEval),
tree_eval(Value, tree(RL,ROp,RR), REval),
Expr =.. [Op,LEval,REval], % is there an easier way to do this?
Eval is Expr.
Now as you notice, this solution has no cuts. They are not necessary, because at a time, only one of the three clauses can be true. For one of the clauses, however, I couldn't come up with a way to make the head unambiguous. This might be of help.
I have the following problem. I have a certain number of facts such as:
parent(jane,dick).
parent(michael,dick).
And I want to have a predicate such as:
numberofchildren(michael,X)
so that if I call it like that it shows X=1.
I've searched the web and everyone puts the children into lists, is there a way not to use lists?
Counting number of solutions requires some extra logical tool (it's inherently non monotonic). Here a possible solution:
:- dynamic count_solutions_store/1.
count_solutions(Goal, N) :-
assert(count_solutions_store(0)),
repeat,
( call(Goal),
retract(count_solutions_store(SoFar)),
Updated is SoFar + 1,
assert(count_solutions_store(Updated)),
fail
; retract(count_solutions_store(T))
),
!, N = T.
I can only see two ways to solve this.
The first, which seems easier, is to get all the solutions in a list and count it. I'm not sure why you dislike this option. Are you worried about efficiency or something? Or just an assignment?
The problem is that without using a meta-logical predicate like setof/3 you're going to have to allow Prolog to bind the values the usual way. The only way to loop if you're letting Prolog do that is with failure, as in something like this:
numberofchildren(Person, N) :- parent(Person, _), N is N+1.
This isn't going to work though; first you're going to get arguments not sufficiently instantiated. Then you're going to fix that and get something like this:
?- numberofchildren(michael, N)
N = 1 ;
N = 1 ;
N = 1 ;
no.
The reason is that you need Prolog to backtrack if it's going to go through the facts one by one, and each time it backtracks, it unbinds whatever it bound since the last choice point. The only way I know of to pass data across this barrier is with the dynamic store:
:- dynamic(numberofchildrensofar/1).
numberofchildren(Person, N) :-
asserta(numberofchildrensofar(0)),
numberofchildren1(Person),
numberofchildrensofar(N), !.
numberofchildren1(Person) :-
parent(Person, _),
retract(numberofchildrensofar(N)),
N1 is N + 1,
asserta(numberofchildrensofar(N1),
!, fail.
numberofchildren1(_).
I haven't tested this, because I think it's fairly disgusting, but it could probably be made to work if it doesn't. :)
Anyway, I strongly recommend you take the list option if possible.