Skip to content
Go back

Data Structures in Prolog

Suggest changes

Table of contents

Open Table of contents

Intro

Like any other programming language, also in Prolog we have data structures, here we will talk about 3 of them:



Thinking in Prolog

Before starting with the data structure let’s set the right mindset with a step-by-step list:

  1. Describe relations, not algorithms.
  2. Prototype queries to discover the needed facts/rules.
  3. Ensure predicates are fully relational unless you really only need one mode.
  4. Test every mode and watch for non-termination.
  5. Use the library for numbers & lists; write your own only when learning.
  6. Add cuts only after the logic is correct.

The cut is a special, zero-argument goal written as !.

max(A, B, A) :- A >= B, !.   % once this succeeds, stop exploring
max(_, B, B).                % otherwise choose the second clausewhat_is_cut.pl

Lists

Syntax

The concrete syntax:

Built-ins for Lists

The number after the slash is not part of the predicate’s name, it states the predicate’s arity (the count of arguments that predicate takes).

Predicate (Arity)PurposeTypical Use
member/2true if Element is in Listmember(X,[a,b,c]).
append/3concatenates or splits listsappend([a,b],[c,d],L).
length/2List ⇄ Length (integer)length(L,3).
reverse/2List ⇄ ReversedListreverse([a,b],R).
select/3remove/insert single elementselect(X,L,R).
nth0/3 / nth1/30- or 1-based indexingnth1(2,[a,b,c],E).
maplist/3..apply Goal to each pair of listsmaplist(succ,In,Out).

All of these are relational: any argument may be a variable (though length/2 requires its second arg ground when generating).

Practice Lists

Build a list which search for 2 consecutive occurencies of an element.

search2(Elem, [Elem, Elem | _]).
search2(Elem, [_ | Rest]) :- search2(Elem, Rest).

Suggest changes
Share this post on:

Next Post
Prolog Overview