Prolog possible removal of elements in a list

前端 未结 2 918
暖寄归人
暖寄归人 2021-01-15 10:17

I have been asked to try to search for all possible outcomes of, removing any numbers from any single elements from a list.

For example, if I have a list X = [1,2,3]

2条回答
  •  遥遥无期
    2021-01-15 10:35

    You have to:

    • select one item (number) from the list
    • replace selected item with a number which is less than the selected item
    • alternatively remove entirely the selected item

    For example:

    remove([N|Tail], [NX|Tail]):-
      succ(N1, N),
      between(1, N1, NX).
    remove([_|Tail], Tail).
    remove([N|Tail], [N|NTail]):-
      remove(Tail, NTail).
    

    The first clause selects the first item in the list, and replaces that item with a number which is less than the item.

    The second clause removes the item from the list (as shown in your examples when you subtract N to the selected item (N) it does not appear in the second list.

    The third clause applies recursion, leaving the head item as-is and applies the procedure to the remaining list.

提交回复
热议问题