Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Concatenation of Lists



Prolog provides an inbuilt method append to concat two Lists.

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.

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

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

NewList = [1,2,a,b,c]

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

NewList = [1,2,3]

yes
| ?- 

Custom Concatenation Implementation

Concatenation of two lists means adding the list items of the second list after the first one. So if two lists are [a,b,c] and [1,2], then the final list will be [a,b,c,1,2]. So to do this task we will create one predicate called list_concat(), that will take first list L1, second list L2, and the L3 as resultant list. There are two observations here.

  • If the first list is empty, and second list is L, then the resultant list will be L.

  • If the first list is not empty, then write this as [Head|Tail], concatenate Tail with L2 recursively, and store into new list in the form, [Head|New List].

Program (list_basics.pl)

list_concat([],L,L).
list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3).

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, 1 lines read - 521 bytes written, 3 ms

yes
| ?- list_concat([1,2],[a,b,c],NewList).

NewList = [1,2,a,b,c]

yes

Concatenating Empty List

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

NewList = [a,b,c]

yes

Concatenating List of List

| ?- list_concat([[1,2,3],[p,q,r]],[a,b,c],NewList).

NewList = [[1,2,3],[p,q,r],a,b,c]

yes
| ?- 

Explanation

  • list_concat([],L,L) represents the base case of the recursive call. In case list is empty, second non-empty List is returned.

  • list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3) represents the recursive case.

    • [X1|L1] is to divide the first list where X1 represents the head of the list and L1 represents the tail of the list.

    • L2 is the second List.

    • [X1|L3] is to get final concatenated List where X1 is appened to top of concatenated sublists represented by L3.

    • list_concat(L1,L2,L3) is the recursive call to List_concat with tail L1 and the second list L2 which is to return a concatenated List as L3.

Advertisements