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!

Help alternating two lists

Status
Not open for further replies.

badkarma082

IS-IT--Management
Sep 11, 2008
4
US
I must develop a function that will accept 3 arguments.
The first two arguments must be a lists.
When either argument is not a list, join_alternate shall display an error message and terminate its processing.
When both arguments are lists, then alternate will produce a new list as its result, as follows:
?- alternate([1,2,3], [a,b,c], R)
R = [1,a,2,b,3,c]
?- alternate([1,2], [a,b,c], R)
R = [1,a,2,b,c]
?- alternate([1], [a,b,c], R)
R = [1,a,b,c]

I would appreciate any help. I just cant figure it out thanks!
 
You must examine all the possibilities :

alternate(X, Y, R)
X is not a list, or Y is not a list, you stop with an error message


Now the cases of end of recursion
alternate([], Y, R)
alternate(X, [], R)

Now the general case
alternate([H1|T1], [H2|T2], R)

 
Still don't really get it, but thanks. I guess learning prolog in 24 hours is not 4 me.

 
So, here is the code in SWI-Prolog :
Code:
alternate(X, Y, _R) :-
	(\+is_list(X); \+is_list(Y)),
	!,
	write('bad args'), 
	nl.


alternate([], R, R).

alternate(R, [], R).

% in the general case, we add H1 and H2 at the list got
% from the lists T1 and T2
alternate([H1 | T1], [H2 | T2], [H1, H2 | R]) :-
	alternate(T1, T2, R).
is_list/1 is a predicate which succeed if is arg is a list. \+ is_list succeed when is_list fails.
 
Wow man you made my day. Thankss!! Now i know this i a little too much, but what if I wanted, to specify which is argument is not a list eg. "list 1 is not valid" or "i list2 is not valid".

 
Jaja thanks man, I really appreciate your help. have a good one.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top