Prolog Combining Two Lists

寵の児 提交于 2019-12-11 06:38:25

问题


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).


来源:https://stackoverflow.com/questions/15018398/prolog-combining-two-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!