簡體   English   中英

從列表中刪除第一個元素,並將該元素附加到 Prolog 中的另一個列表

[英]Removing the first element from a list, and appending that element to another list in Prolog

正如標題所述,我有四個單獨的列表。 我希望能夠做的是:

/* 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 非常陌生,並且仍在努力解決它。 是否有更簡潔的方法來根據某些約束對列表項的這種移動進行編碼?

TL;DR:您在 OP 中提供的兩個偽代碼不匹配!


以下基於兩個假設:

  1. 必須達到一個固定點。 畢竟,您在其中一條評論中寫道:

    基本上,我知道最后一個事實(在移動項目之后,如果有奇數數量的項目),每個列表將有偶數數量的項目

  2. 一個偽代碼就是你的目標。

    \n /* 偽代碼(不在序言中).. */\n如果(大小(列表1)%2 == 1){\n     /* 取出 List1 的頭部,並將其移動到 List2 */\n }\n if(size(List2) % 2 == 1) {\n     /* 取出 List2 的頭部,並將其移至 List3 */\n }\n if(size(List4) % 2 == 1) {\n     /* 將 List4 的頭部移到 List2 */\n\n如果(大小(列表3)%2 == 1){\n     /* 將 List3 的頭部移到 List4 */\n }\n

壞消息:上面的“代碼”可能無法到達固定點(滿足第一個約束)!

作為反例,請考慮以下循環( 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM