Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - List Access Predicates



Prolog provides various predicates to perform actions on the list. Following is the list of useful predicates to access elements of the List −

Predicate Usage
member(Element, List) Succeeds if Element is part of the 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.

Example - member(Element, List)

member predicates succeeds if Element is a part of the List.

Output

| ?- member(b, [a, b, c]).  % true as b is member of the list.

true ? 

(15 ms) yes
| ?- member(d, [a, b, c]).  % no as d is not a member of the list. 

no
| ?- member(X, [a, b, c]).  % get all members of the List

X = a ? a

X = b

X = c

(16 ms) yes
| ?- 

Example - length(List, Length)

length predicate unifies the Length with the size of the list.

Output

| ?- length([a, b, c], L).   % gets length of List in L

L = 3

yes
| ?- length(X, 3).  % create list of three uninstantiated variables

X = [_,_,_]

yes
| ?- 

Example - select(Element, List, RemainingList)

select predicate succeeds if Element is removed from the List.

Output

| ?- select(2, [1, 2, 3, 2, 4], R).

R = [1,3,2,4] ? 

yes
| ?- 

Example - nth0(Index, List, Element)

nth0 predicate is used to access 0 index based element of the list.

Output

| ?- nth0(1, [a, b, c, d], E).

E = b

yes
| ?-

Example - nth1(Index, List, Element)

nth1 predicate is used to access 1 index based element of the list.

Output

| ?- nth1(1, [a, b, c, d], E).

E = a

yes
| ?-
Advertisements