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

后端 未结 6 2074
北海茫月
北海茫月 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:23

    Since Prolog has append which only accepts lists, why don't we use it to insert our element in one of the lists. i.e.

    % E = element, L = list, R = result
    % e.g. add_elem_in_list ([1,2,3,4], 5, R).
    add_elem_in_list(L, E, R) :- append(L, [E], R).
    

提交回复
热议问题