Create a recursive function in prolog

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 7K views
Wez
can anyone help me out with this please
i want to create a recursive function in prolog to do the following thing

sum lists(X; Y;Z) holds for lists X = [x1; : : : xn], Y = [y1; : : : yn] and
Z of numbers if and only if Z = [z1; : : : zn] and zi = xi+yi (1  i  n).
 
Physics news on Phys.org


This is 'Hello World' level for lists in Prolog.

For starters create a 'function' that sums a list.

sum([1,2,3],X).
X = 6.

You should get the idea.

Do you self study Prolog?
 


yeah i do...i have that one done...but i wanted for two list

e.g [1,2,3,4] and [1,2,3,4] would output [2,4,6,8]

and for the second would be how many elements are repeated

e.g [1,2,3,4] and [1,6,7,4] would output 2

thanks
 


First, state it in a logical manner. For instance,

Z is the sum of lists X and Y iff Z_i = X_i + Y_i. This is good, but this is not a recursive enough definition to be implemented directly in prolog. Perhaps a better way of saying the same thing would involve mentioning the first elements of the lists X, Y, and Z, and then what has to be true of the lists' tails...

So you would write:

listSum(X, Y, Z) :- < something about the lists' heads > , <something about the lists' tails>.
 


Are you familiar with the syntax of the lists? namely [H|T]? Notice that you can use [H|T] for your 'return' variable not just for 'incoming' variable this is what I mean:

e.g.

Code:
sum([1,2,3,4,5],Sum,ReverseSteps).
Sum = 15
ReverseSteps = [15, 14, 12, 9, 5]]

you are familiar with this

Code:
sum([],0).
sum([H|T],Sum):-
    sum(T,Sum1),
    Sum is Sum1 + H.

the only thing I can think you are not familiar is to pass something back in the list like this

Code:
sum1([],0,[]).
sum1([H|T],Sum,[Sum|ReturnList]):-
    sum1(T,Sum1,ReturnList),
    Sum is Sum1 + H.

the solution to your original problem is similar in concept to this - how to use the return of predicate in the list. In the example it made sense to jump into recursion in first step, it is not so in your problem.

HTH.
 


Aside. If you are using SWI Prolog, I recommend to use the debugger for tracing the execution - it is not great but it helps.
 


Code:
sum(X,Y,Z) :- X == [], write(over).
sum(X,Y,Z) :- [Tmp1 | X_new] = X, [Tmp2 | Y_new] = Y, Tmp is Tmp1 + Tmp2, [ Tmp | Z ]=Z1 , sum(X_new, Y_new, Z1) .