list - 从列表中删除第一个元素,并将该元素 append 到 Prolog 中的另一个列表中

标签 list prolog append

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

/* 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

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

最佳答案

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


以下内容基于两个假设:

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

    Basically, I know for a fact that at the end (after moving items around if there are an odd amount of items), that each list will have an even amount of items.

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

    /* 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 */
    }
    

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

作为反例,请考虑以下循环 ( 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 = [] : 返回步骤1

关于list - 从列表中删除第一个元素,并将该元素 append 到 Prolog 中的另一个列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884613/

相关文章:

prolog - SWI Prolog 水壶拼图

javascript - 将 html append 到 Bootstrap 模式不起作用

java - 将 Set<T> 转换为 List<T> 的最简洁方法

list - 如何在序言中转置矩阵

python - 根据 Python 中列表中的值返回一个字符串值

prolog - 如何在 Prolog 中读入文件名?

python - 如何将 "python --version"的输出 append 到 bash shell 中的文件?

javascript - 如何 append 一些代码并使其与已加载的 js 一起工作?

Python:- 从电子邮件列表中拆分电子邮件(逗号、空格分隔)

python - 如何提取扩展名并保存而不重复?