I'm trying to write prolog program that sums items from two lists and present the result in another list.
For example:
List1:
[1, 3, 4, 2]
List2:
[5, 1, 3, 0]
Result:
[6, 4, 7, 2]
So far, I have this:
list_sum([],[],[]).
list_sum([H1|T1],[H2|T2],L3):-list_sum(T1,T2,[X|L3]), X is H1+H2.
?-list_sum([1,2,3,4],[1,2,3,4],R),write(R).
If you use SWI-Prolog you can use maplist, and module lambda found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl :
:- use_module(library(lambda)).
list_sum(L1, L2, L3) :-
maplist(\X^Y^Z^(Z is X + Y), L1, L2, L3).
What #gusbro said. Further, you need to rearrange the order of operations and add a couple of additional special cases to deal with lists of differing lengths:
list_sum( [] , [] , [] ) .
list_sum( [] , [Y|Ys] , [Z|Zs] ) :- Z is 0+Y , list_sum( [] , Ys , Zs ) .
list_sum( [X|Xs] , [] , [Z|Zs] ) :- Z is X+0 , list_sum( Xs , [] , Zs ) .
list_sum( [X|Xs] , [Y|Ys] , [Z|Zs] ) :- Z is X+Y , list_sum( Xs , Ys , Zs ) .
You need to move the evaluation (Z is X+Y) in my example above, so that Z is evaluated before the recursion. This accomplishes two things:
First, it makes the predicate tail-recursive, meaning the solution is iterative and therefore doesn't consume stack space. In your code, the evaluations aren't performed until after the entire recursion is done. Each intermediate sum is kept on the stack and is evaluated right-to-left on your way back up. This means you'll blow your stack on a large list.
Second, evaluating each result before recursing down means you fail fast. The first sum that doesn't unify with the result fails the entire operation. Your solution fails slow. Consider 10,000,000 item lists where the first item doesn't sum to the first item in the result list: you'll traverse all 10,000,000 items, then — assuming you didn't blow your stack — you start evaluating sums right-to-left. Your predicate won't fail until the very last evalution.
it's one liner in SWI-Prolog:
list_sum(X,Y,S) :- maplist(plus, X,Y,S).
And it works also 'backward':
?- maplist(plus, [1,2,3],Y,[3,4,5]).
Y = [2, 2, 2].
You are almost there.
Your problem is that the result of the sum should be put in the head of the second clause, and not in the recursive call!
list_sum([H1|T1],[H2|T2],[X|L3]):-list_sum(T1,T2,L3), X is H1+H2.
Note that the way you had written it, L3 which is "returned" in as a result is a list in which you have removed the head (X) from the recusive call; whereas you meant the opposite: to add an element (X) to the resulting list.
the result should be a list, so you can't just say X is H1+H2 because X is not a list and you are only matching head of the lists with a single variable. also list_sum([],[],0) is not correct for same reason. the answer looks like this:
sum([],[],[]).
sum([H1| T1], [H2| T2], [ResH| ResT]) :-
sum(T1, T2, ResT),
ResH is H1+H2.
but when you run your own code, first X is matched with H1+H2, on the second recursive call X has a value and can not be matched with head of T1+T2. so it outputs a no.
domains
list=integer*
predicates
add(list,list,list)
clauses
add([],[],[]).
add([V1X|X],[V1Y|Y],[V1Z|Z]):-add(X,Y,Z),V1Z=V1X+V1Y.
Related
I want to implement the prolog predicate prefixSum(L, R) that calculates the prefix sum of a list i.e:
?- prefixSum([1,2,3,4],R).
R=[1,3,6,10].
Here is my solution so far:
prefixSum([],[]).
prefixSum([X], [X])
prefixSum([X|Xs], [R, Rs|T]):-
Rs is X + R, prefixSum(Xs, T).
What can I try next?
Your original code,
prefixSum( [] , [] ) .
prefixSum( [X] , [X] )
prefixSum( [X|Xs] , [R,Rs|T] ) :- Rs is X+R, prefixSum(Xs,T) .
Has these problems:
The code is syntactically incorrect, as the 2nd clause is not terminated by ..
In the 3rd clause, the variable R will always be unbound unless you've provided a bound list as the 2nd argument to prefixSum/3, meaning Rs is X+R will fail.
The key to what you are trying to accomplish is that as you traverse the list, you need to track the sum previously computed as you go.
That leads to an implementation like this:
prefix_sum( [] , [] ) . % the empty list is a special case
prefix_sum( [X|Xs] , [X|Ys] ) :- % for a non-empty list, we add the first item to the result , and
prefix_sum(Xs,X,Ys) . % invoke our helper, seeding the previous sum with the first element.
prefix_sum( [] , _ , [] ) . % once the source list is exhausted, we're done.
prefix_sum( [X|Xs] , P , [Y|Ys] ) :- % otherwise...
Y is P+X, % compute the sum of the current element and the previous sum
prefix_sum(Xs,Y,Ys) . % and recurse down on the tails.
prefix_sum(L, Ps) :-
prefix_sum_(L, 0, Ps).
prefix_sum_([], _, []).
prefix_sum_([H|T], S, [P|Ps]) :-
P is H + S,
prefix_sum_(T, P, Ps).
Result in swi-prolog:
?- prefix_sum([1,2,3,4], Ps).
Ps = [1, 3, 6, 10].
This is an operation on lists knows as a "scan" which, unlike a "fold", keeps a list of intermediate results. For your particular case you could use the built-in plus/3 but you might also need to define a helper predicate like add/3:
add(X, Y, Z) :- Z is X + Y.
Now you can do:
?- foldl(add, [1,2,3,4], 0, Sum).
Sum = 10.
?- scanl(add, [1,2,3,4], 0, [0|Sums]).
Sums = [1, 3, 6, 10].
If you don't like the useless addition of the zero you can split off the first element in advance, so:
?- [1,2,3,4] = [V0|Vs], scanl(add, Vs, V0, Result).
V0 = 1,
Vs = [2, 3, 4],
Result = [1, 3, 6, 10].
"Scan left" and "fold left" are available in library(apply) in SWI-Prolog and your exact question is solved in the examples on the docs for scanl. You can also look at the implementation of scanl.
Yes, this answer is perfectly good. When I look at the solution and compare it to the library definition of scanl/4 I just see a generic algorithm that has been specialized to solve one particular instance by binding the Goal.
Im trying to split a list into 2 in prolog. But im still new to this and any help would be much appreciated.
My problem is:
Implement a clause choose(N,L,R,S) that chooses N items from L and puts them in R with the remaining elements in L left in S
This is what i have tried so far:
split(0,_L1,_L2,_L4).
split(X,[H|T],L1,T):-
X>0,
X1 is X-1,
split(X1,T,[H|L1],T).
When i try to run
split(2,[1,2,4,5],X,Y).
false
This is the result i get. What am i doing wrong?
If X > 0, the first element of the L list must also be the first element of the R list. For example, this should hold: split(1, [a | Rest], [a], Rest). If we want this relationship to hold, we must express it in the head of a rule.
Your second clause should therefore look more like this:
split(X, [H|T], [H|L1], Rest) :-
X > 0,
X1 is X - 1,
split(X1, T, L1, Rest).
This splits off the prefix all right, but the rest is not right yet:
?- split(2, [1, 2, 4, 5], R, S).
R = [1, 2|S] ;
false.
You need to think again about the case where 0 elements are to be split off. What should be the result of split(0, [a, b, c], R, S)?
You biggest problem is the way in which you are constructing/deconstructing the 3rd argument.
And you're missing a special case.
Most recursive problems has a couple of special, usually terminating, cases and one general case. This problem has two special cases.
The general case is simple. You'll note here that we unify the third argument with [X|Pfx]. This adds X to the head of the left/prefix result, and gives us its (likely unbound) tail. That tail gets passed down in recursion.
partition( N , [X|Xs] , [X|Pfx] , Sfx ) :-
N > 0 ,
N1 is N-1 ,
partition( N1, Xs, Pfx, Sfx )
.
[You might notice that we're building a list in the 3rd argument (the prefix list) as we go along... but it's not a legal list: the tail is presumably unbound. We'll take care of that at the end.
So...that takes care of the general case. But, how do we know when we're done?
One special/terminating case is when the source list is exhausted. If that happens before N decrements to 0, we're done. We can handle that like this:
partition( _ , [], [], [] ).
We don't really care what the value of N is, but it might be useful to enfoce the constraint that N >= 0. What's happening here is that when the source list (the 2nd argument) is exhausted and is empty list, we (1) close the prefix list (3rd argument) and unify the suffix list with the empty list.
The next special case is when N is finally decremented to zero. That's no more complex:
partition( 0 , Sfx, [], Sfx ).
We unify whatever is left of the source list with the suffix list (4th argument) and close the prefix list with the empty list.
The remaining special case is when N is finally decremented to 0. That's just as simple. Here's:
partition( 0 , Xs, [], Xs ).
Put it all together and you get:
partition( _ , [] , [] , [] ).
partition( 0 , Sfx , [] , Sfx ).
partition( N , [X|Xs] , [X|Pfx] , Sfx ) :-
N > 0 ,
N1 is N-1,
partition( N1, Xs , Pfx , Sfx ).
Again a Prolog beginner :-}
I build up a list element by element using
(1)
member(NewElement,ListToBeFilled).
in a repeating call,
(2)
ListToBeFilled = [NewElement|TmpListToBeFilled].
in a recursive call like
something(...,TmpListToBeFilled).
A concrete example of (2)
catch_all_nth1(List, AllNth, Counter, Result) :-
[H|T] = List,
NewCounter is Counter + 1,
(
0 is Counter mod AllNth
->
Result = [H|Result1]
;
Result = Result1
),
catch_all_nth1(T,AllNth,NewCounter,Result1),
!.
catch_all_nth1([], _, _, _).
As result I get a list which looks like
[E1, E2, E3, ..., Elast | _G12321].
Of course, the Tail is a Variable. [btw: are there better method to fill up the
list, directly avoiding the "unassigned tail"?]
I was now looking for a simple method to eliminate the "unassigned tail".
I found:
Delete an unassigned member in list
there it is proposed to use:
exclude(var, ListWithVar, ListWithoutVar),!,
[Found this too, but did not help as I do not want a dummy element at the end
Prolog list has uninstantiated tail, need to get rid of it ]
What I noticed is that using length\2 eliminate the "unassigned tail", too, and in addtion
the same List remains.
My Question is: How does it work? I would like to use the mechanism to eliminate the unassigned tail without using a new variable... [in SWI Prolog 'till now I did not get the debugger
entering length() ?!]
The example:
Z=['a','b','c' | Y],
X = Z,
write(' X '),write(X),nl,
length(X,Tmp),
write(' X '),write(X),nl.
13 ?- test(X).
X [a,b,c|_G3453]
X [a,b,c]
X = [a, b, c] .
I thought X, once initialized can not be changed anymore and you need
a new variable like in exclude(var, ListWithVar, ListWithoutVar).
Would be happy if someone explain the trick to me...
Thanks :-)
You're right about the strange behaviour: it's due to the ability of length/2 when called with unbound arguments
The predicate is non-deterministic, producing lists of increasing length if List is a partial list and Int is unbound.
example:
?- length([a,b,c|X],N).
X = [],
N = 3 ;
X = [_G16],
N = 4 ;
X = [_G16, _G19],
N = 5 ;
...
For your 'applicative' code, this tiny correction should be sufficient. Change the base recursion clause to
catch_all_nth1([], _, _, []).
here are the results before
4 ?- catch_all_nth1([a,b,c,d],2,1,R).
R = [b, d|_G75].
and after the correction:
5 ?- catch_all_nth1([a,b,c,d],2,1,R).
R = [b, d].
But I would suggest instead to use some of better know methods that Prolog provide us: like findall/3:
?- findall(E, (nth1(I,[a,b,c,d],E), I mod 2 =:= 0), L).
L = [b, d].
I think this should do it:
% case 1: end of list reached, replace final var with empty list
close_open_list(Uninstantiated_Var) :-
var(Uninstantiated_Var), !,
Uninstantiated_Var = '[]'.
% case 2: not the end, recurse
close_open_list([_|Tail]) :-
close_open_list(Tail).
?- X=[1,2,3|_], close_open_list(X).
X = [1, 2, 3].
Note that only variable X is used.. it simply recurses through the list until it hits the var at the end, replaces it with an empty list, which closes it. X is then available as a regular 'closed' list.
Edit: once a list element has been assigned to something specific, it cannot be changed. But the list itself can be appended to, when constructed as an open list ie. with |_ at the end. Open lists are a great way to build up list elements without needing new variables. eg.
X=[1,2,3|_], memberchk(4, X), memberchk(5,X).
X = [1, 2, 3, 4, 5|_G378304]
In the example above, memberchk tries tries to make '4', then '5' members of the list, which it succeeds in doing by inserting them into the free variable at the end in each case.
Then when you're done, just close it.
I'm new to Prolog and I can't seem to get the answer to this on my own.
What I want is, that Prolog counts ever Number in a list, NOT every element. So for example:
getnumbers([1, 2, c, h, 4], X).
Should give me:
X=3
getnumbers([], 0).
getnumbers([_ | T], N) :- getnumbers(T, N1), N is N1+1.
Is what I've got, but it obviously gives me every element in a list. I don't know how and where to put a "only count numbers".
As usual, when you work with lists (and SWI-Prolog), you can use module lambda.pl found there : http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
:- use_module(library(lambda)).
getnumbers(L, N) :-
foldl(\X^Y^Z^(number(X)
-> Z is Y+1
; Z = Y),
L, 0, N).
Consider using the built-in predicates (for example in SWI-Prolog), and checking their implementations if you are interested in how to do it yourself:
include(number, List, Ns), length(Ns, N)
Stay logically pure, it's easy: Use the meta-predicate
tcount/3 in tandem with the reified type test predicate number_t/2 (short for number_truth/2):
number_t(X,Truth) :- number(X), !, Truth = true.
number_t(X,Truth) :- nonvar(X), !, Truth = false.
number_t(X,true) :- freeze(X, number(X)).
number_t(X,false) :- freeze(X,\+number(X)).
Let's run the query the OP suggested:
?- tcount(number_t,[1,2,c,h,4],N).
N = 3. % succeeds deterministically
Note that this is monotone: delaying variable binding is always logically sound. Consider:
?- tcount(number_t,[A,B,C,D,E],N), A=1, B=2, C=c, D=h, E=4.
N = 3, A = 1, B = 2, C = c, D = h, E = 4 ; % succeeds, but leaves choice point
false.
At last, let us peek at some of the answers of the following quite general query:
?- tcount(number_t,[A,B,C],N).
N = 3, freeze(A, number(A)), freeze(B, number(B)), freeze(C, number(C)) ;
N = 2, freeze(A, number(A)), freeze(B, number(B)), freeze(C,\+number(C)) ;
N = 2, freeze(A, number(A)), freeze(B,\+number(B)), freeze(C, number(C)) ;
N = 1, freeze(A, number(A)), freeze(B,\+number(B)), freeze(C,\+number(C)) ;
N = 2, freeze(A,\+number(A)), freeze(B, number(B)), freeze(C, number(C)) ;
N = 1, freeze(A,\+number(A)), freeze(B, number(B)), freeze(C,\+number(C)) ;
N = 1, freeze(A,\+number(A)), freeze(B,\+number(B)), freeze(C, number(C)) ;
N = 0, freeze(A,\+number(A)), freeze(B,\+number(B)), freeze(C,\+number(C)).
of course, you must check the type of an element to see if it satisfies the condition.
number/1 it's the predicate you're looking for.
See also if/then/else construct, to use in the recursive clause.
This uses Prolog's natural pattern matching with number/1, and an additional clause (3 below) to handle cases that are not numbers.
% 1 - base recursion
getnumbers([], 0).
% 2 - will pass ONLY if H is a number
getnumbers([H | T], N) :-
number(H),
getnumbers(T, N1),
N is N1+1.
% 3 - if got here, H CANNOT be a number, ignore head, N is unchanged, recurse tail
getnumbers([_ | T], N) :-
getnumbers(T, N).
A common prolog idiom with this sort of problem is to first define your predicate for public consumption, and have it invoke a 'worker' predicate. Often it will use some sort of accumulator. For your problem, the public consumption predicate is something like:
count_numbers( Xs , N ) :-
count_numbers_in_list( Xs , 0 , N ) .
count_numbers_in_list( [] , N , N ) .
count_numbers_in_list( [X|Xs] , T , N ) :-
number(X) ,
T1 is T+1 ,
count_numbers_in_list( Xs , T1 , N )
.
You'll want to structure the recursive bit so that it is tail recursive as well, meaning that the recursive call depends on nothing but data in the argument list. This allows the compiler to reuse the existing stack frame on each call, so the predicate becomes, in effect, iterative instead of recursive. A properly tail-recursive predicate can process a list of infinite length; one that is not will allocate a new stack frame on every recursion and eventually blow its stack. The above count_numbers_in_list/3 is tail recursive. This is not:
getnumbers([H | T], N) :-
number(H),
getnumbers(T, N1),
N is N1+1.
I need to write a program in Prolog that should remove every second element of a list. Should work this: [1,2,3,4,5,6,7] -> [1,3,5,7]
so far I have this, but it just returns "false".
r([], []).
r([H|[T1|T]], R) :- del(T1,[H[T1|T]], R), r(R).
del(X,[X|L],L).
del(X,[Y|L],[Y|L1]):- del(X,L,L1).
This is pretty much Landei's answer in specific Prolog syntax:
r([], []).
r([X], [X]).
r([X,_|Xs], [X|Ys]) :- r(Xs, Ys).
The second predicate is not required.
Alternative solution using foldl/4:
fold_step(Item, true:[Item|Tail], false:Tail).
fold_step(_Item, false:Tail, true:Tail).
odd(List, Odd) :-
foldl(fold_step, List, true:Odd, _:[]).
Usage:
?- odd([1, 2, 3, 4, 5, 6, 7], Odd).
Odd = [1, 3, 5, 7]
The idea is to go through the list, while keeping "odd/even" flag and flipping its value (false -> true, true -> false) on each element. We also gradually construct the list, by appending those elements which have "odd/even" flag equal to true, and skipping others.
This fine answer by #code_x386 utilizes difference-lists and foldl/4.
Let's use only one fold_step/3 clause and make the relation more general, like so:
fold_step(X, [X|Xs]+Ys, Ys+Xs).
list_odds_evens(List, Odds, Evens) :-
foldl(fold_step, List, Odds+Evens, []+[]).
Sample queries:
?– list_odds_evens([a,b,c,d,e,f], Odds, Evens).
Evens = [b,d,f], Odds = [a,c,e]
?– list_odds_evens([a,b,c,d,e,f,g], Odds, Evens).
Evens = [b,d,f], Odds = [a,c,e,g]
Edit
Why not use one clause less and do away with predicate fold_step/3?
lambda to the rescue!
:- use_module(library(lambda)).
list_odds_evens(List, Odds, Evens) :-
foldl(\X^([X|Xs]+Ys)^(Ys+Xs)^true, List, Odds+Evens, []+[]).
Another possibility is to use DCGs, they are usually a worthwhile consideration when describing lists:
list_oddindices(L,O) :-
phrase(oddindices(L),O). % the list O is described by oddindices//1
oddindices([]) --> % if L is empty
[]. % O is empty as well
oddindices([X]) --> % if L has just one element
[X]. % it's in O
oddindices([O,_E|OEs]) --> % if L's head consists of at least two elements
[O], % the first is in O
oddindices(OEs). % the same holds for the tail
This is certainly less elegant than the solutions using foldl/4 but the code is very easily readable, yet it solves the task described by the OP and works both ways as well:
?- list_oddindices([1,2,3,4,5,6,7],O).
O = [1, 3, 5, 7] ;
false.
?- list_oddindices(L,[1,3,5,7]).
L = [1, _G4412, 3, _G4418, 5, _G4424, 7] ;
L = [1, _G4412, 3, _G4418, 5, _G4424, 7, _G4430] ;
false.
I have no Prolog here to try it out, and I got a little bit rusty, but it should be along the lines of
r([]) :- [].
r([X]) :- [X].
r([X,Y|Z]) :- R=r(Z),[X|R].
[Edit]
Of course pad is right. My solution would work in functional languages like Haskell or Erlang:
--Haskell
r [] = []
r [x] = [x]
r (x:_:xs) = x : (r xs)
In Prolog you have to "pull" the right sides into the argument list in order to trigger unification.
I just needed a function like this and took a more "mathematical" approach:
odds(Xs, Ys) :- findall(X, (nth1(I,Xs,X), I mod 2 =:= 1), Ys).
It doesn't work both ways like some of the other fine answers here, but it's short and sweet.