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

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

    You can't modify lists in Prolog, but you can create a list with an unspecified length:

    main :-
        A = [1,2,3,4|_].
    

    Then, you can insert an element using nth0/3 in SWI-Prolog:

    :- initialization(main).
    
    main :-
        A = [1,2,3,4|_],
        nth0(4,A,5),
        writeln(A).
    

    After this element is inserted, A = [1,2,3,4,5|_].

    You can also define a function that appends an item to the end of a list in-place, and then use it like this:

    :- initialization(main).
    
    append_to_list(List,Item) :-
        List = [Start|[To_add|Rest]],
        nonvar(Start),
        (var(To_add),To_add=Item;append_to_list([To_add|Rest],Item)).
    
    main :-
        A = [1,2,3|_],
        append_to_list(A,4),
        append_to_list(A,4),
        writeln(A).
    

    In this example, A = [1,2,3,4,4|_] after these two items are appended.

提交回复
热议问题