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

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

    As the others have pointed out, you're going to be stuck with the performance issue.
    But just as an exercise I decided to try and create a predicate that could append an element to the end of a list, without using append.

    % add_tail(+List,+Element,-List)
    % Add the given element to the end of the list, without using the "append" predicate.
    add_tail([],X,[X]).
    add_tail([H|T],X,[H|L]):-add_tail(T,X,L).
    

    I would advice that you'd simply use the append function, as a built-in function it is likely to be faster than anything manually crafted.

提交回复
热议问题