【问题标题】:Removing the first element from a list, and appending that element to another list in Prolog从列表中删除第一个元素,并将该元素附加到 Prolog 中的另一个列表
【发布时间】:2016-02-26 08:38:54
【问题描述】:

正如标题所述,我有四个单独的列表。我想要做的是:

/* Pseudo-code (not in prolog).. */
if(size(List1) % 2 == 1) {
    /* Take the head of List1, and move it to List2 */
}
if(size(List2) % 2 == 1) {
    /* Take the head of List2, and move it to List3 */
}
if(size(List4) % 2 == 1) {
    /* Take the head of List4 and move it to List2 */
}
if(size(List3) % 2 == 1) {
    /* Take the head of List3 and move it to List4 */
}

所以,如果我有这种格式:list(contents, list_name) 以及以下事实:

list([1,2,3,4], List1).
list([5,6,7], List2).
list([8,9,10], List3).
list([11,12,13,14], List4).

% validList(ListNo,ListTransfer).
% If ListNo has an odd number of items, we can move any item to the list, ListTransfer).
validList(List1,List2).
validList(List2,List3).
validList(List2,List4).
validList(List4,List3).

我写这个是为了检查它,但我不确定我是否走在正确的道路上:

checkList(ListFrom,ListTo):-
    1 is mod(size(ListFrom), 2), % Check to see if size of list is odd
    ListFrom = [Head|Tail],      % it is, so we grab the head of the list
    append(Head, ListTo, ListTo).% we then append it to the correct list

我对 prolog 非常陌生,并且仍在努力解决它。是否有更简洁的方法来根据某些约束对列表项的这种移动进行编码?

【问题讨论】:

  • list modulo 2 是什么意思(指你的伪代码)?
  • 例如,move it to list2 是什么意思?到list2的头?结束?你首先说我有两个单独的列表,但你的伪代码表示四个。
  • 某些 cmets(例如,/* Take the head of List2 and move it to List4 */)似乎是错误的。请清除它们的有效性或编辑您的问题并更正它们。
  • @lurker 抱歉,再次更新。我的意思是将它移动到特定列表中的任何位置。稍后我将重新排序列表。
  • @repeat 是什么?基本上,我知道最后(在移动项目后,如果有奇数数量的项目),每个列表将有一个偶数数量的项目。

标签: list prolog append


【解决方案1】:

TL;DR:你在OP中给出的两个伪代码不匹配!


以下基于两个假设:

  1. 要达到一个固定点。毕竟,您在其中一个 cmets 中写道:

    基本上,我知道最后(如果有奇数个项目,在移动项目之后),每个列表将有一个偶数个项目

  2. 第一个伪代码是您的目标。

    /* 伪代码(不在序言中).. */ 如果(大小(列表 1)% 2 == 1){ /* 取 List1 的头部,并移动到 List2 */ } 如果(大小(列表 2)% 2 == 1){ /* 取出 List2 的头部,并将其移动到 List3 */ } 如果(大小(列表 4)% 2 == 1){ /* 取 List4 的头部并移动到 List2 */ 如果(大小(列表 3)% 2 == 1){ /* 取 List3 的头部并移动到 List4 */ }

坏消息:上面的“代码”可能没有达到一个固定点(满足第一个约束)!

作为反例,考虑以下循环 (2->3->4->2):

  1. L1 = [], L2 = [2], L3 = [], L4 = []:取L2的头,移到L3

  2. L1 = [], L2 = [], L3 = [2], L4 = []:取L3的头,移到L4

  3. L1 = [], L2 = [], L3 = [], L4 = [2]: 把L4的头移到L2

  4. L1 = [], L2 = [2], L3 = [], L4 = []:回到第一步

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2020-10-29
    • 2022-11-13
    • 2018-08-30
    • 2015-04-24
    相关资源
    最近更新 更多