Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - List Manipulation Predicates



Prolog provides various predicates to manipulate list. Following is the list of useful predicates to manipulate elements of the List −

Predicate Usage
append(List1, List2, Result) appends List2 to List and returns Result as resulted List.
reverse(List, ReversedList) Reverves the List and returns ReversedList.
sort(List, SortedList) Sorts the List and returns SortedList.
msort(List, SortedList) Sorts the List using merge sort while preseving the duplicates and returns SortedList.

Example - append(List1, List2, Result)

append predicates append List1 to List2 and set the updated list to Result. It can be used to get prefix or suffix of the lists.

Output

| ?- append([a, b], [c, d], X).

X = [a,b,c,d]

yes
| ?- append(X, [c, d], [a, b, c, d]). % find the prefix

X = [a,b]

yes
| ?- append([a, b], X, [a, b, c, d]). % find the suffix

X = [c,d]

yes
| ?- 

Example - reverse(List, ReversedList)

reverse predicate reverses the List and stores in ReversedList.

Output

| ?- reverse([a, b, c], R).   % reverse the list

R = [c,b,a]

yes
| ?- 

Example - sort(List, SortedList)

sort predicate sorts the List using standard order while removing the duplicates and stores in SortedList.

Output

| ?- sort([3, 1, 4, 1, 5, 9, 2], S). % sort the list

S = [1,2,3,4,5,9]

yes
| ?- 

Example - msort(List, SortedList)

msort predicate sorts the List using merge sort while preserving the duplicates and stores in SortedList.

Output

| ?- msort([3, 1, 4, 1, 5, 9, 2], S). % sort the list

S = [1,1,2,3,4,5,9]

yes
| ?- 
Advertisements