Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - List Operators



Prolog handles List in a very natural way. It is very easy to create and manipulate List in Prolog. Although there are no standard operators to work with List but Prolog provides various predicates to perform actions on the list. Following is the list of useful operators and predicates −

Operator Meaning
| List Constructor, | (Vertical Bar)
[] Empty List
[element1, element2,...] To create list of element1, element2,...

Common List Predicates

Predicate Usage
member(Element, List) Succeeds if Element is part of the List.
append(List1, List2, Result) appends List2 to List and returns Result as resulted List.
length(List, Length) Unifies Length as the size of the List.
select(Element, List, RemainingList) Succeeds if Element is removed from the List and remaining elements are returned as RemainingList.
nth0(Index, List, Element) Accesses the Element from the List using zero based index.
nth1(Index, List, Element) Accesses the Element from the List using one based index.
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.

List Constructor, | (Vertical Bar)

Vertical Bar is the main operator to construct a List in Prolog.

Syntax

[Head | Tail]

Where −

  • Head − represents the first element of the list. We can have multiple elements in Head section as well.

  • Tail − represents the remaining elements of the list.

Example

| ?- [H | T] = [1, 2, 3, 4, 5].

H = 1
T = [2,3,4,5]

yes
| ?- [First, Second | Rest] = [a, b, c, d, e].

First = a
Rest = [c,d,e]
Second = b

(16 ms) yes
| ?- 

Empty List, []

Empty List is a special atom to represent list of no items. It acts as a base case for all Lists.

Syntax

[]

List using literals, [element1, element2,...]

List using literals is a syntactic sugar replacing repeated use of | and [].

For example, if we want to create a list of 1,2,3.

[1 | (2 | (3 | []))]

We can create above list as shown below −

[1, 2, 3]
List Predicates For Access with Examples List Predicates For Manipulation with Examples
Advertisements