Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Appending to a List



Append into List

Appending two lists means adding two lists together, or adding one list as an item. Now if the item is present in the list, then the append function will not work. So we will create one predicate namely, list_append(L1, L2, L3). The following are some observations −

  • Let A is an element, L1 is a list, the output will be L1 also, when L1 has A already.

  • Otherwise new list will be L2 = [A|L1].

Program (list_basics.pl)

list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_append(A,T,T) :- list_member(A,T),!.
list_append(A,T,[A|T]).

In this case, we have used (!) symbol, that is known as cut. So when the first line is executed successfully, then we cut it, so it will not execute the next operation.

Output

| ?- consult('D:/TP Prolog/Sample Codes/list_basics.pl').
compiling D:/TP Prolog/Sample Codes/list_basics.pl for byte code...
D:/TP Prolog/Sample Codes/list_basics.pl compiled, 3 lines read - 877 bytes written, 4 ms

yes
| ?- list_append(a,[e,i,o,u],NewList).

NewList = [a,e,i,o,u]

yes
| ?- list_append(e,[e,i,o,u],NewList).

NewList = [e,i,o,u]

yes
| ?- list_append([a,b],[e,i,o,u],NewList).

NewList = [[a,b],e,i,o,u]

yes
| ?- list_append(e,[e,i,o,u],NewList).

NewList = [e,i,o,u]

yes

Explanation

  • list_member(X,[X|_]). is base case to check if X is a head element of the List.

  • list_member(X,[_|TAIL]) :- list_member(X,TAIL). is a recursive call to check if X is member of tail of the List.

  • list_append(A,T,T) :- list_member(A,T),!. is base case, if A is already a member of List, then skip the next operation.

  • list_append(A,T,[A|T]) appends A to T as adding it as a head element of T and returning the updated list.

We can use Prolog inbuilt append function to add an element to the List where element is to be passed as a list of one element.

Syntax

append(List1, List2, AppendedList)

Where

  • List1 − First List.

  • List2 − Second List

  • AppendedList − The resulted List of concatenation of two above lists.

It returns true if lists are concatenated otherwise false.

Appending a List to a List

GNU Prolog 1.5.0 (64 bits)
Compiled Jul  8 2021, 12:33:56 with cl
Copyright (C) 1999-2021 Daniel Diaz

| ?- append([1],[a,b,c],NewList)
.

NewList = [1,a,b,c]

yes
| ?- append([],[1,2,3],NewList).

NewList = [1,2,3]

yes
| ?- 

Appending an element to a List fails.

GNU Prolog 1.5.0 (64 bits)
Compiled Jul  8 2021, 12:33:56 with cl
Copyright (C) 1999-2021 Daniel Diaz

| ?- append(1,[a,b,c],NewList).

no
| ?- 
Advertisements