Prolog 删除列表中第一个和最后一个元素之间的元素 [英] Prolog Remove the elements between the first and the last elements in a list

查看:29
本文介绍了Prolog 删除列表中第一个和最后一个元素之间的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图只保留仅包含连续整数的列表的第一个元素和最后一个元素.

I am trying to keep only the first element and the last element for a list which contains only consecutive integers.

例如:

?- remove([1,2,3,4,5], NewList).
NewList = [1,5].

我只能成功保留最后一个元素:

I can only successfully keep the last element:

remove([], []).

% for consecutive integers in the list
remove([ Head | Tail ], NewList) :-
    check_consecutive(Head, Tail),
    remove(Tail, NewList).

% for the case when the list is empty
remove([ Head | Tail ], [ Head | NewList ]) :-
    not(check_consecutive(Head, Tail)),
    remove(Tail, NewList).

check_consecutive(Num, [ Head | _ ]) :-
    Num is Head - 1.

我一直想保留第一个元素,但它一直给我最后一个元素.

I have been tying to keep the first element, but it keeps giving me the last element.

如果有一些不连续的元素,它应该这样做:

If there are some elements which is not consecutive, it should do some thing like:

?- remove([1,2,4,5,6,8,3], NewList).
NewList = [[1,6], 8, 3]. 

感谢任何帮助.

推荐答案

要解决这个问题,你必须处理不同的情况,这里是解决方案,然后是评论:

To solve this problem you have to handle different cases, here the solution then the comment:

last([E],E).
last([_|T],E):-
    last(T,E).

remove([],[]).
remove([A],[A]).
remove([A,B],[A,B]).
remove([A|B],[A,Last]):-
    last(B,Last).

findElementsR([A,B],LT,LOT,LO):-
    B =< A,
    append(LT,[A],LT1),
    remove(LT1,LRem),
    append(LOT,[LRem,[B]],LO).

findElementsR([A,B|T],LT,LOT,LO):-
    B =< A,
    append(LT,[A],LT1),
    remove(LT1,LRem),
    append(LOT,[LRem],LOT1),
    findElementsR([B|T],[],LOT1,LO).

findElementsR([A,B],LT,LOT,LO):-
    B is A+1, %consecutive
    append(LT,[A,B],LTO),
    remove(LTO,RM),
    append(LOT,[RM],LO).

findElementsR([A,B|T],LT,LOT,LO):-
    B is A+1, %consecutive
    append(LT,[A],LTO),
    findElementsR([B|T],LTO,LOT,LO).

findElements(L,LO):-
    findElementsR(L,[],[],LO).

?- findElements([3,1,2,3,2,3,4,5,2,3,4],L).
L = [[3], [1, 3], [2, 5], [2, 4]]
false

所以,首先,我定义了 last/2,它简单地将列表作为输入,返回最后一个元素

So, first of all, i've defined last/2 that simply, given a list as an input, returns the last element

?- last([1,2,3],L).
L = 3

然后使用 remove/3 我得到第一个和最后一个元素组成的列表.

Then with remove/3 i get the list composd by th first and the last element.

findElements/2 用于调用 findElementsR/4 (使其尾递归).findElements/4 查找连续元素的列表,然后调用 remove/2 获取第一个和最后一个.

findElements/2 is used to call findElementsR/4 (to make it tail recursive). findElements/4 finds a list of consecutive elements and then calls remove/2 to get the first and the last.

这篇关于Prolog 删除列表中第一个和最后一个元素之间的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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