Prolog分成两个列表问题 [英] Prolog separating into two lists issue

查看:20
本文介绍了Prolog分成两个列表问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个序言作业.

我需要查看列表中的第一个项目,看看它的后续项目是否相同,直到它们不同为止,然后将列表按第一个项目及其重复项分开.例如,如果我的列表是 a、a、a、b、c,它会将其分成第一个:a、a、a.第二:b,c.

I need to look at the first item in a list, see if its following items are the same until they are not and separate the lists by the first item and its duplicates. e.g if my list was a,a,a,b,c it would separate it into first: a,a,a. second: b,c.

我当前的解决方案有效,只是最终匹配项进入第二个列表,而不是第一个.我似乎想不出办法让它出现在第一个列表中.

My current solution works except that the final matching item comes into the second list, not the first. I can't seem to think of a way to get it to appear in the first list instead.

grab([],[],[]).
grab([A,A|L],[A|L2],Rest) :- grab([A|L],L2,Rest).
grab([A|L],Init,[A|L2]) :- grab(L,Init,L2).

推荐答案

当前两个元素不同时,您不需要递归目标.

When the first two elements are different you do not need a recursive goal.

grab([], [], []).
grab([A,A|Rest], [A|As], L2):- !, grab([A|Rest], As, L2).
grab([A|Tail], [A], Tail).

这篇关于Prolog分成两个列表问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆