Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

adding H and T in list

Status
Not open for further replies.

charlene1225

IS-IT--Management
Apr 18, 2009
1
MY
I'm new in prolog.
May I ask, if I wanna add the H and Tail in a list separately,how should i write??

for example, i have list [[3,12],[4,5]].
and I want the output become H = 7,T = 17.
 
You don't understand what mean Head and Tail in Prolog.
In Prolog, as in Lisp, you acces to the first element of a list (often named Head) and the rest of this list (often named Tail).
Code:
1 ?- L = [1,2,3,4], L = [H | T].
L = [1, 2, 3, 4],
H = 1,
T = [2, 3, 4] ;
false.
So, I think that you want to add the elements of the list column by column.
There are differents ways to do that
First you use an accumulator to memorize the results
Code:
% when the list is empty, it'over
% but the results are in a reverse order
add_list1([[],[]], L1, L2) :-
	reverse(L1, L2).

% I add the first elements of the list
% I memorize the result in the middle list
% I carry on with the rest
add_list1([[H1 | T1], [H2 | T2]], L, LF) :-
	H3 is H1 + H2,
	add_list1([T1, T2], [H3 | L], LF).
Call : add_list1([[3,12],[4,5]], [], L).
Another way is to travel through the list and construct the result by the end.

Code:
% when there is nothing in the lists
% the result is empty
add_list2([[],[]], []).

% I construct the result list by the end
% I first built the result list with the tails of the first list
% I put the sum of the elements at the head of the result list.
add_list2([[H1 | T1], [H2 | T2]], [H3 | T3]) :-
	add_list2([T1, T2], T3),
	H3 is H1 + H2.
Call : add_list2([[3,12],[4,5]], L).


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top