Prolog Combining Two Lists

2019-07-25 08:09发布

问题:

I am new to prolog and would appreciate any help on the following question:

I need to write a program that accepts two lists and appends the second to first and displays this new list and its length. I know that prolog might have some built in functions to make this all easier...but I do not want to use those.

eg: newlist([a,b,c],[d,e,f],L3,Le). would return L3=[a,b,c,d,e,f] and Le=6

Here is what I have so far:

newlist([],List,List,0) 

newlist([Element|List1],List2,[Element|List3],L) :- newlist(List1,List2,List3, LT), L is LT + 1.

This does the appending correctly but I can only get the length of the first list instead of the combined list. Is there a way for me to add the second list's length to the first to get the combined list length?

Thanks, and sorry if this question is rather easy...I am new.

回答1:

Is there a way for me to add the second list's length to the first to get the combined list length?

You should replace:

newlist([],List,List,0).

with:

newlist([],List,List,X):-length(List,X).