How do you append an element to a list in place in Prolog?

后端 未结 6 2059
北海茫月
北海茫月 2021-02-18 15:45

If I have a list in Prolog such as X = [1, 2, 3, 4], how do I add the element 5 to the end of the list to have X = [1, 2, 3, 4, 5]?

The append function needs two lists

6条回答
  •  甜味超标
    2021-02-18 16:24

    One declarative solution is to use a difference list (as Daniel suggested in its answer). A difference list gets its name from being usually represented as a difference between two lists: a list and its tail. For example, an empty list can be represented as T-T. A list with the elements 1, 2, and 3 can be represented as [1,2,3| T]-T (note that (-)/2 is standard built-in infix operator). The advantage of this representation is that you can append an element to a list in constant time by using a single fact definition of the append/3 predicate:

    append(L1-T1, T1-T2, L1-T2).
    

    An usage example:

    ?- append([1,2,3,4| T1]-T1, [5| T2]-T2, Result).
    T1 = [5|T2],
    Result = [1, 2, 3, 4, 5|T2]-T2.
    

    If necessary, is not difficult to convert between a "normal" list and a difference list. I leave that as an exercise to you.

提交回复
热议问题