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

查看:57
本文介绍了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天全站免登陆