删除列表的中间元素

删除列表的中间元素

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

问题描述

我想编写一个Prolog程序,以将奇数列表中的中间元素删除到另一个列表中.

例如,如果我们给出: delete_mid([1,2,3,4,5],L),那么它将产生: L = [1,2,4,5] 作为答案.

解决方案

我很惊讶也有点难过,到目前为止,这两个答案都没有采用最明显的方法;当然,您已经在学校听说过它(我怀疑这可能是OP所期望的).

然而,解释或立即做有点困难,所以首先,这里是找到中间元素的谓词:

  list_mid([H | T],Mid):-list_mid_1(T,T,H,Mid).list_mid_1([[,, _,Mid,Mid).list_mid_1([_,_ | Fast],[S | Slow],__,Mid):-list_mid_1(快,慢,S,中). 

我希望名字很明显.

 ?-list_mid([],Mid).错误的.?-list_mid([x],Mid).中= x.?-list_mid([a,x,b],Mid).中= x.?-list_mid([a,a,x,b,b],Mid).中= x.?-list_mid([a,a,x,b],Mid).错误的. 

似乎可以正常工作.现在,我可以尝试添加该零件,以保持其当前所扔掉的东西.


我很忙,所以花了一段时间.同时,劳布绍格的答案正是我所想到的.我没有看到它,而是这样写的:

  delete_mid([H | T],L):-delete_mid_1(T,T,H,L).delete_mid_1([[,Rest,_,Rest).delete_mid_1([_,_ | Fast],[H | Slow],Prev,[Prev | Back]):-delete_mid_1(快,慢,H,后退). 

这不像Raubsauger的解决方案那么整洁,但似乎其他解决方案都是相同的.对于测试用例,它以@false终止.


我认为 list_middle/2 谓词就足够了;再次让我感到惊讶和难过的是,只有劳勃绍格(Raubsauger)看到了(或已经知道).


Undtäglichgrüßtdas Murmeltier

I want to write a Prolog program to delete the middle element from an odd-numbered list into another list.

For example, If we give : delete_mid([1,2,3,4,5],L) then it will produce : L = [1,2,4,5] as answer.

解决方案

I am surprised and a bit saddened that neither answer so far takes the most obvious approach; surely you've heard about it in school (and I suspect it might be what OP is expected to do).

It is however a bit difficult to explain or do at once, so first, here is a predicate to find the middle element:

list_mid([H|T], Mid) :-
    list_mid_1(T, T, H, Mid).

list_mid_1([], _, Mid, Mid).
list_mid_1([_,_|Fast], [S|Slow], _, Mid) :-
    list_mid_1(Fast, Slow, S, Mid).

I hope the names are obvious.

?- list_mid([], Mid).
false.

?- list_mid([x], Mid).
Mid = x.

?- list_mid([a,x,b], Mid).
Mid = x.

?- list_mid([a,a,x,b,b], Mid).
Mid = x.

?- list_mid([a,a,x,b], Mid).
false.

Seems to work. Now, I can try and add the part where it keeps what it throws away at the moment.


I was busy so this took a while. In the meantime, the answer by Raubsauger is exactly what I had in mind. I did not see it and instead wrote this:

delete_mid([H|T], L) :-
    delete_mid_1(T, T, H, L).

delete_mid_1([], Rest, _, Rest).
delete_mid_1([_,_|Fast], [H|Slow], Prev, [Prev|Back]) :-
    delete_mid_1(Fast, Slow, H, Back).

It is not as neat as the solution by Raubsauger but it seems it is otherwise the same solution. It terminates for the test cases by @false.


I thought the list_middle/2 predicate was enough; I am again surprised and a bit saddened that only Raubsauger saw it (or already knew that about it).


Und täglich grüßt das Murmeltier

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

08-11 19:36