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!

Small List problem

Status
Not open for further replies.

529

Programmer
Nov 23, 2010
1
LT
Hi :),

I'm new to prolog and it's a bit difficult to understand some concepts, i was trying to connect list elements into one list con([[1,2,3],[a]],Result) into R=[1,2,3,a] , but the main problem i encountered was that i can't find a way to add up those list elements together i only succeed in adding the first one R=[1,2,3|G_624]:

add([],_). %we work with first element until list is empty
con([],_). %we do the same thing with the whole list

con([X|T],Result):-
add(X,Result); %Here Result changes to R=[1,2,3] instead of R=[[1,2,3]]and after another recursion should be R=[1,2,3,a] but for some reason Result does not add up :?
con(T,Result).

add([H|T],[H|R]):-
add(T,R).

What i am doing wrong? it's probably the adding changed result to Result, for some reason it doesn't add up more elements than one.

Hope you can help :)

 
As a matter of fact, you are not adding any element at all. The version of 'add' just copies one list to another but it's a little bit flawed.

Code:
add([H | T], [H | R]) :-
      add(T, R).
add([], []).

... would be the functional version in this case. You see, when you use: add([], _) you don't provide a meaningful result in case the first list is empty. You just say that if the list is empty, then the result can be anything (that's the meaning of '_'). This is why you get _G624 in your global answer.

So maybe you want to work some more on this idea of 'end of recursivity' and get back later if you still didn't make it. Please note that there are predefined predicates that perform concatenation of lists, try help(append) at the Prolog prompt for an example.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top