<<

The Functional Side of Programming

Massimo Marchiori

Department of Pure and Applied Mathematics

UniversityofPadova

Via Belzoni Padova Italy

maxhilbertmathunipdit

between functional and logic programming its outcome was Abstract

a transformation from a lo cal class of logic programs to

In this pap er we study the relationships b etween logic pro

functional programs that is sound that is informally ev

gramming and trying to answer

erything calculated by the obtained functional program is

the following basic question to what extent is logic pro

calculated by the original logic program to o

gramming just functional programming in disguise We

However Reddys transformation fails to identify a func

develop a theory to formally express this corresp ondence

tional class of logic programming for various reasons

and exhibit a class that can by right b e considered as the

First for the transformation to b e sound the target func

functional core of logic programming Moreover since the

tional language must employanad ho c fairparallel reduc

functional meaning of each program in this class is provided

tion strategy This means that the translation of a logic

constructively via a transformation from logic to functional

program its functional meaning is not a pure functional

programs we showhow the obtained theoretical results are

program which is quite unsatisfactoryWe also remark that

useful also in the study of languages integration termination

from a practical p oint of view not only the obtained co de

issues and practical implementations

cannot in general run on any implementation not supp orting

fair paralleli sm but even using a parallel functional language

an eective use is unfeasible indeed the degree of paral

Intro duction

lelism required is far b eyond the so called orparalleli sm

of logic programming which is already considered imprac

During the recentyears a huge amount of eort was devoted

tical since even shallowbacktracking can instigate an ar

to integrating the two paradigms of functional programming

bitrary numb er of innite computations see also b elow

and logic programming and to develop languages combining

Second the transformation is not complete thatisthe

them see for instance However much less attention

obtained functional program may not terminate despite the

was devoted to the basic problem of studying what are the

original logic program terminates Of course this is unac

intimate relationshi ps b etween logic programming and func

ceptable for a functional class of logic programs a mini

tional programming So far the research only scratched the

mal requirement should b e that its transformed functional

surface nding out the dierences eg usage of unication

program b ehaves just in the same way not losing a funda

versus matching vs reduction nondeterminism

mental prop ertylike termination in fact we guess Reddy

vs determinism etc see for example but not the

was aware of this problem since alb eit not mentioning the

connections that is howmuchtheydohave in common To

lack of completeness he only refers to his transformation as

the b est of our knowledge only Reddy eg in tried

being sound

to shed some light on this fundamental topic

In this pap er we aim to answer the following basic ques

Thus Reddys transformation only started shaping the

tion to what extent is logic programming just functional

b orders of the problem In fact the rst thing that should

programming in disguise That is to say what class of logic

b e claried is what means for a logic program to b e func

programs can b e considered the functional core of logic pro

tional in nature As hinted b efore this should mean it is

gramming

equivalent to a functional program b ehaving in the same

A rst requirementwe imp ose on such a class if it ex

way hence the need for a transformation from logic to func

ists is to b e a neat sublanguage of logic programming one

tional programs to nd out the functional meaning How

should b e able to sayofevery clause of a logic program

ever the problem lies in what b ehaving in the same way

whether it is functional or not the functional avor should

should signify A natural resp onse is requiring the trans

a fundamental prop erty visible at clause level This will b e

formation to functional programs to b e complete thatisto

referred to as lo cality every class we consider henceforth

preserve termination and computed answers this wayan

will b e understo o d to b e lo cal

external observer should not see any dierence on what the

Reddy in his work started studying the relationships

program computes Completeness is a minimal requirement

but still is not the full answer since it do es not rule out

Turingcarp et lowlevel transformations such a transfor

mation would b e complete for the whole class of logic pro

grams hence identifying logic programming with functional

Backtracking due to nondeterminism is implemented via parallel

pro cesses

Failure of a goal to resolve with a clause

We will consider functional programs of the following programming a not very interesting result This is nothing

P

more than a restatementoftheChurchTuring thesis ev

op pat e

P

ery other Turingcomplete paradigm for calculation would

op pat e

b e equivalenthaving the same computational p ower

of function kind a nite sequence

The answer we found is to slightly stress the notion of

P

op pat e

n n

n

equivalence we said an external observer should not see

denitions where the op are operators not necessarily dis

i

any dierence on what the program computes Wealsore

tinct the pat are patterns and the e are expressions As

i

i

quire he should not see any dierence on how the program

usual in this basic functional language op erators are func

computes it should not increase in time complexityMore

tion symb ols that cannot o ccur in patterns patterns are

formally logic programs b elonging to a certain complexity

linear terms and expressions are terms We remark that

class should b e transformed into functional programs of the

patterns in a program can also b e overlapping that is two

same or lower complexity class This turns out to b e a

or more pat s in the denitions of some op erator could b e

i

go o d answer with this requirement a class can b e found

uniable in which case the dierent alternatives are tried

that is maximal among those complete A great surprise is

out one at a time from top to b ottom

that this result holds all the same even if the requirementis

considerably weakened we can allow the transformation to

As far as the reduction strategy is concerned in accor

arbitrarily worsen the time complexity of a program pro

dance to what said ab ove on the generality of the language

vided only this worsening is computable

weleaveitunspecied thatistosay all the results weare

going to prove should hold indep endentl y on the particular

These results will b e proven rst on denite logic pro

reduction strategy b e it strict or lazy when this is not the

gramming and then also extended to normal logic program

case we will say it explicitly

ming where use of negation is allowed

Given a functional program F and an expression ewe

Also as a bypro duct of these corresp ondence results we

will indicate with F e the result of reducing e wrt F

will showhow such transformational metho dology can pro

vide new contributions to a clean integration of logic and

Lo cality

functional programming and to the study of termination

prop erties for logic programs Finallywe will test this ap

We study classes of logic programs under a lo cal p ointof

proach from a practical p oint of view b enchmarking the

view that is requiring their description can b e given clause

co de pro duced by the transformation

byclause

Denition A class of logic programs is said to b e local

Preliminaries

when every program b elongs to it i each of its clauses do es



Notation

Such lo cal classes are very useful b ecause as mentioned in

Sequences of terms will b e written in vectorial notation eg

the Intro duction they allow to neatly dene a sublanguage

t and jtj denotes their length viz if t t t m

m

of logic programming simply restricting the syntax of each

then jtj m Sequences in formulas should b e seen just as

program clause to those characterizing the class

abbreviations for instance t with t t t denotes

m

Non lo cal classes instead are in general not very useful

the string t t Accordingly given two sequencess

m

for dening a sublanguage not only do they require the

s s and t t t s t stands for the sequence

n m

programmer to takeinto account many program lines all at

s s t t

n m

once but in case of program development two fundamental

Given a family S of ob jects terms atoms etc VarS

op erations like deleting a clause or adding a clause of the

is the set of all the variables contained in it moreover S

class to the program can b e dangerous indeed they are

is said to b e linear if no variable o ccurs more than once

b oth safe op erations if and only if the class is lo cal

in it To makeformulas more readable we will sometimes

Thus from nowonwe assume that every class of logic

omit brackets from the argument of unary functions eg

programs we talk ab out is understo o d to b e lo cal

f g X may b e written fgX

Also we will consider in full generality classes that can

For standard logic programming terminologywewill

constrain b oth the logic program and the goal for nota

mainly follow Logic programs will b e considered as

tional convenience we will talk by abuse of a class of logic

executed with leftmost selection rule and depthrst search

programs meaning a collection b oth of logic programs and

rule that is the standard way in which logic programming

of goals

is implemented for example in With mgu s twe

indicate a most general unier of two terms s and t

e

Functionally Mo ded Programs

Finally IN stands for the set IN f g of natural numbers

extended with the ordinal

The starting idea is quite natural since logic programming

deals with relations whereas functional programming deals

Functional Programs

with functions we could try to give some directionality to

the predicates turning them into functions Indeed Reddy

To give relevance to a characterization of a functional core

in followed this path employing the concept of mo d

of logic programs the considered functional language should

ing

not employ features particular to a given language but in

stead b e somehow the common kernel of the various ML

Denition A mode for a nary predicate p is a map

Haskell Miranda and so on The functional language con

from f ng to fin out gAmoding is a map asso ciating

sidered here is to a certain extent the most basic p ossible

to every predicate p a mo de for it A modedprogram is

it just has function denition with patterns

a program endowed with a mo ding An argument p osition

of a mo ded predicate is called input resp output if it is

Miranda is a trademark of Research Software Ltd

mapp ed by the mo de into in resp out 

So some other condition should b e imp osed on the out If m is a mo ding we sometimes write pm mk

put arguments but what Intuitivelywe will require the or simply mmk to show the mo de of a k ary

output arguments of a predicate to b e dierentvariables In predicate p Also ps t denotes a mo ded atom p having its

deed recall the idea that led to constraining the input argu input p ositions lled in by the sequence of termss and its

ments analogously viewing a predicate as a function from output p ositions lled in by t

its input to its output arguments should imply we cannot

A mo ded predicate can b e roughly seen as a function

predict in advance the result But if some output argument

from its input arguments to its output ones For instance

is not a variable this means weknowinadvance something

a predicate p with mo ding in in out should b e viewed as

ab out the output and analogously if some variable o ccurs

a function having two inputs the rst two arguments and

more than once in dierentarguments The prop er formal

one output the third one

ization of this idea is

Some conditions are needed to ensure this informal in

terpretation of mo ded programs is assured

Denition A goal p s t p s t is Func

n n n

tional ly Moded if it is Well Mo ded and the sequence t t The idea is to identify the concept of b eing an input

n

is linear and comp osed only of variables argument with a datum that do es not need to b e pro cessed

A program is said to b e Functional ly Moded FM if its further b eing an input its value should b e xed and well

every clause p t s p s t p s t isWell determined a safe condition is to require the datum to b e

n n n n

Mo ded the sequence t t is linear and t t is com ground so that its value cannot b e mo died by some calcu

n n

p osed only of variables  lation if some variable is present it could b e instantiated to

some term hence mo difying the datum This is formalized

For instance it is immediate to check that the program

via the following denition

seen in Example is Functionally Mo ded

It is interesting to notice that many parts of logic pro

Denition Aderivation is data driven if in it every

gramming co des are written more or less consciously in the

time an atom is selected for unication in a goal the input

functional form given by this class Also a great deal of

arguments of the atom are ground 

basic logic programs likeegappend reverse quicksort

The syntactical criterion used by Reddy to imp ose direc

member etc b elong to it

tionality on logic programs is the Well Mo ding

We remark how the ab ove denition concerns denite

logic programs only ie programs without negation In

Denition A goal p s t p s t is Wel l

n n n

Section the full denition of the class for normal logic

S

i

programs ie with negation will b e given Vart Moded if i nVars

j i

j

A program is said to b e Wel l Moded WM if for eachof

its clauses p t s p s t p s t wehave

Semantics n n n n

S

i

i n Vars Vart 

i j

j

Supp ose a logic program P is run with goal G Let us denote

with answer the rst obtained answer it is equal to

PG

This denition roughly says that every variable in an

input arguments of the b o dy hence according to our in

i

if the computation terminates successfully giving

tended interpretation required as input by some predicate

as computed answer substitution

must app ear earlier in the clause as an output argument t

j

Fail if the computation terminates with failure

so it must have b een calculated

if the computation do es not terminate

Example The usual program to add twonumbers

In case the user can activate backtracking to lo ok for the

addXX

second answer answer and so on till for some k

PG

addsXYsZ addXYZ

answer k returns Fail or in case of innite answers

PG

with mo ding addin in out is WellMo ded 

we assume k and answer

PG

Now the answer semantics  G of a logic program P

P

Well Mo dedness is an appropriate criterion since

wrt a goal G is dened as the p ossibly innite sequence

Theorem If P and G arerespectively a Wel l

 G answer answer k

P PG PG

Modedprogram and goal then every derivation of P fGg

is data driven

We can nowprovide a formal denition of termination

Using Well Mo dedness Reddy in intro duced a trans

Denition A program P is said to terminate wrt a

formation of Well Mo ded logic programs into parallel func

goal G if  G with 

P k k

tional programs This transformation as said in the Intro

duction was there proved to b e sound that is informally

This kind of termination is usually referred to as universal

everything calculated by the obtained functional program is

see eg to distinguish it from existential termination

calculated by the original logic program to o

viz we will come back on other kinds of termina

tion later in Section and Subsection

The ab ove result however gives only one side of the

coin since the transformation is not complete the obtained So far was considered a sp ecial symb ol to indicate

functional programs might not terminate As said in the nontermination however in the following it may also in

Intro duction this is not satisfactory since completeness is a dicate a nonterminating expression we will write e

minimal requirement that should b e asked of a logic program for some expression e meaning that e is a nonterminating

which is inherently functional The problem is that so far expression in the given functional program Also for nota

only input arguments were considered imp osing on them a tional convenience we will allow usage of every answer as

direction groundness via the Well Mo ding criterion but substitution in the sp ecial cases Fail resp we

output arguments were neglected assume e Fail resp e for every expression e

n

D D x y y t

n

xy y t

n



n

D D Fail Fail

xy y t

n



n

xjFail Fail D D

xy y t

n



n n

D D J x y y v J t D v

n

xy y t xy y t

n n

 

n n

v J Failv D D D

xy y t xy y t

n n

 

n n

D D J x jFailv D v

xy y t xy y t

n n

 

n n

D D J x jJ u v w D J x juJx jv w

xy y t xy y t

n n

 

n n

J u J v w J J u v w D D D

xy y t xy y t

n n

 

n n

D D xjJ u v D J x ju xjv

xy y t xy y t

n n

 

Table The Datahandler equations schema

Logic programming is intrinsicall y nondeterministi c mul Completeness

tiple choices are pro cessed via backtracking to utilize this

Denition A transformation for a class of logic

feature into functional programming weuseabinarysym

programs is a computable map sending goals of into ex

bols J as pairing op erator to J oin together the dierent

pressions and logic programs of into functional programs

p ossibili ti es arising from the nondeterminism For instance



if in the logic program a predicate p is nondeterministi

cally dened via two clauses p q and p r in the corre

Denition A transformation is said to b e complete

sp onding functional program we will join these two dierent

for a class of logic programs if there is a computable func

choices via the single rule p J q r

tion A such that for every program P and goal G

A constant Fail will b e used to denote failure of a logic

P terminates wrt G implies

program derivation

We will also employ socalled Datahand ler op erators

A VarG P G  G 

P

n

A Datahandler of the form D can b e roughly seen as

t t

 

The presence of VarG in the ab ove formulaistomake

the function t t ie it exp ects a datum of the form t

explicit that to get a computed answer substitution wehave

and gives as output t this is formalized by the rule D

to rememb er the names of the variables presentinGwe

of Table The dierence is that it also has to cop e with

could however shorten the denition omitting VarG since

dierent structures than t namely when the J and the

the variable names could b e enco ded directly in the trans

Fail op erators crop up the sup erscript n helps to determine

formation G of the goal

what structures are in principle p ossible This is illustrated

Observe that for a complete if P terminates wrt G

by the remaining rules D D of Table Essentiallyit

then also P terminates wrt G that is is termina

pro duces a failure whenever a Fail result is found rules D

tion preserving indeed if it is not the case then P G

D otherwise it pro cesses the rst result among the ones

and so also A Var G P G a contra

joined with J ifitist resp a failure then via rule D

diction since  Gdoesnotcontain by assumption

P

n

resp D D the Datahandler D transforms it into

t t

 

The Transformation

t resp skips it and go es on pro cessing the other results

The transformation we will nowintro duce is composi

Denition If G ps tisFunctionally Mo ded

tional that is for every two programs P and Q P Q

jtj

P Q for a suitable map Hence we can describ e it

then Gis D ps

X X X X

 

 

jtj jtj

giving its denition only for a goal a clause and the map

If P p t s p s t p s t isFunction

n n n n

ally Mo ded then P is

From nowonwe will assume that the goal is of the

form ps t this is not restrictive since eg a Func

The equation

tionally Mo ded goal of the form p s t p s t

n n n

can b e split into a goal ps t t and a clause

n

jt j jt j

n

n

ps t t p s t p s t where p is a new

p t D D

n n n n

NV nt s NV nt NV njp s

n n n

n n

predicate that are b oth Functionall y Mo ded giving an equiv

alent program This assumption is not necessary but it is

jt j



adopted since it shortens some denitions and results

D t

NV t NV jp s

  

n

n

where NV k Vars n Vart

j j

j k

j k

jt j jt j

Incidentallyobserve that by the denition of Functionally

n

n

p t D D

Mo ded program it follows NV

NV nt s NV nt NV njp s

n n n

n n

For every predicate ps tinP the Datahandler equa

jt j



D NV jp s

jt j

tions for D see Table and the otherwiseequation

NV t NV jp s

  

t t

px Fail

otherwise We will assume this mo dication in the following

examples

n

in the equa For every o ccurrence of a function D

Example Consider the well known app end program

tion of p oint the corresp onding Datahandler equations

used to split a list ie with mo ding appendoutoutin we

see Table 

will refer to this usage of app end as splitapp end

The idea b ehind the transformation is that every clause

append XX

appendAXYAZ appendXYZ

p t s p s t p s t

n n n n

The transformation of the rst clause yields

appendX X provides an equation dening p t ie p applied to its

input arguments Its output value s is obtained in the

append X Fail

n

following way

and the transformation of the second gives

Informally NV k for k n denotes the V ariables

AappendZ appendAZ D of p p that are N eeded for the input arguments of

k

AXY AjXY

p p and for the output argument of the head pred

k n

append X Fail 

icate p ies s

k n

We start with the input data t Then applying the

Denition map

jt j



Let a function M b e dened this way

rst Datahandler D we calculate

NV t NV jp s

  

P P P P

p s that gives its output values for t together with

Mflhs rhs gP QNflhs rhs gQ MP Q

the values from t that are needed in the sequel to calcu

MfgQfg

P P Q Q

late some other p s or the nal outputs ie NV

i i n

Nflhs rhs g flhs rhs gQ

P Q

The pro cess go es on till all the p p have b een pro

n

if mgu lhs lhs then

p P Q P P

jt j

n

flhs J rhs rhs gNflhs rhs gQ

cessed and the last Datahandler D sim

P P

NV nt s

n

n

else Nflhs rhs gQ

p P

ply passes to the nal outputs the values previously

n

Nflhs rhs g fgfg

computed presentinNV n t

n

A graphical representation of the followed approachis

Let normalize b e a function that deletes from its input

illustrated in Figure

program S all the otherwiseequations and app ends at the

end of the program new otherwiseequations corresp onding

In p ointanotherwiseequation that is an equation

to all the op erators in S

where the pattern is a variable is intro duced indeed just

Then P Q normalize MP Q P Q

like in a logic program a failure o ccurs when the selected

atom of the goal do not unify with every clause head here



when no other equation is applicabl e to solve a function

The function M can b e expressed in this equivalent more

the otherwiseequation is selected pro ducing Fail as result

readable way

having a variable as pattern ensures it b ehaves like a catch

Q

Q

P P

all

op t e

op s e

Q

Q P P

s e op

t e op

Note that the Datahandler equations pro duced bypoints

and Q be Let P be

and of the transformation can b e deduced from the sin

gle equation pro duced in hence for brevity from nowon

P P

Q

Q

op s e

op t e n

n n

n

m n

we will omit them in program listings

Then MP Q is simply

Another useful simplication can b e obtained observ

ing that in the equation of p oint the rightmost Data

P P Q P Q

fop s J e e mgu op s op t g

i i j

i i i

j j

handler can b e applied rightaway to the argumentt

Indeed since NV the rightmost Datahandler is

where the equations are ordered lexicographica ll y wrt i j

jt j



viz the indexes i of the rst program P have precedence

D if the clause is a fact ie the b o dy is empty and

t s

 

over the indexes j of the second program Q

jt j



The b ehaviour of the map should b e quite clear First

D otherwise

t NV jp s

  

employing M whenever two equations overlap in some cases

Hence p oint can b e mo died saying that the corre

insert an equation that J oins them for these cases only this

sp onding equation is

is why a most general unier is used via the binary symbol

J Then the original equations are concatenated to cop e

p t s

with the other cases Finally the result is normalized

in the sense that the otherwiseequations are placed in the

when the clause is a fact and

correct p osition at the end to work prop erly

p s t p s t

n n n

B B B

J

J

B B B

B B B

J

J

B B B

B B B

J

J

BN BN

BN

D D D D

Qk

Q

Q

Q

Q

Q

Q

Q

Q

Q

Q

Q

Q

Q

Q

Q

p t s

n

Figure Dataow representation of a clause p t s p s t p s t

n n n n

Although as it is works ne a useful improvementis

ajFail J a Ja D D

to get rid of useless equations via the following transition D

AXY AjXY X X X X

   

rule

D J a Ja Fail

D

X X X X

   

P fop pat e g Q fop pat e gR

pat pat

P fop pat e gQ R

J a D Ja Fail

D

X X X X

   

expressing the fact that the equation op pat e can b e

J a Ja D Fail

deleted since op pat e will b e always selected b efore

D

X X X X

   

We will assume this simplicati on is added to the denition

of in the further examples

J a Ja Fail

D



Example The transformation of the program split

app end cf Example is

From Theorem it easily follows

appendAZ J AX D AappendZ

Corollary The transformation is complete

AXY AjXY

appendX J XFail

append X Fail 

Mo dular Programming

An imp ortant feature of the transformation is that it in

Theorem Let G ps t and P aprogram both

tegrates well with mo dular programming Indeed let us

Functional ly Moded If  G then

P k

denote with the mo dule relation that is PQ if P

do es not dene predicatesfunctions that are dened in Q

P G J t Jt Jt t

k k

The transformation is mo dulepreservin g in the sense that

Example We will calculate all the p ossible splittings

Q P Q Lemma P

of the list a via the translation by of the splitapp end

program

to b e fussy note that actually if PQ some Datahandler

The goal is appendXYa that is transformed via

equation dened in P could b e rep eated in Q b esides

this is not a problem in practice it can b e xed via a suitable

appenda into D

renaming of the Datahandler equations

X X X X

   

Also the comp ositional b ehaviour of gets simpler

Reducing this expression yields when a Datahandler

equation is applied it is indicated under the equality sym

Q P Q P Q Lemma P

b ol

Hence when dealing with mo dules b ecomes program com

p osition

app enda D

X X X X

   

Thanks to Lemmata and all the b enets of mo d

ular programming can b e retained when passing from logic

ajapp end J a D D

AXY AjXY X X X X

   

to functional programming mo duleslibra ries in logic pro

gramming can b e translated into corresp onding mo dules of

J a D ajJ Fail D

X X X X AXY AjXY

the target functional language Also in pro ject development

   

this avoids global retransformation in case a single mo dule

Ja ajFail J a D D

is mo died

D

AXY AjXY X X X X

   

Complexity Beyond Completeness

As said in the Intro duction we are going to use complexity As wehave seen completeness suces to prove the Opti

arguments to provide a suitable notion of functionality mality Theorem However from a practical p oint of view

We take as time complexity of a logic program resp we could b e interested in a stronger corresp ondence This

of a functional program P which is run with a goal resp happ ens when we are not interested in all the answers of a

an expression G the numb er of resolution steps resp of logic program but only in part of them For instance if

 G the logic program yields one answer and

P

rewrite steps it p erforms and denote this measure by C P G

a complete transformation could not grasp this information

Having dened a suitable measure of the execution time of

b ecause the program is nonterminating A natural wayto

a program it makes sense to talk ab out the corresp onding

x this problem is to employ a lazy reduction strategy for

complexity classes with resp ect to this measure Nowwe

the functional program and dening a corresp onding notion

have at our disp osal a mean to say when a class of logic

of completeness However westick to the generality require

programs is inherently functional in nature it must havea

ments expressed in Subsection and dene an extension

transformation that translates every logic program in into

of completeness that also preserves the answers contained

a functional program having the same or lower complexity

in a nonterminating logic program disregarding the sp ecic

This is expressed by the following denition

reduction strategy

Denition A transformation for a class of logic

Denition A transformation is said to b e hyper

programs is said to b e complexity preserving if there is a

complete for a class of logic programs if there are two

k IN such that for every program P and goal G

families A and B of computable functions

n n

nIeN nIeN

C P G k C P G 

such that for every program P and goal G if

 G then

P k

Observe that the linear factor k is necessary to ensure the

indep endence of the particular unity measure employed

e

i IN A VarG P B G

i i

minik

With the aid of this new requirement we can formalize



the vague concept of b eing functional

If for a transformation hyp ercompleteness holds when

Denition A class of logic programs is functional

the reduction strategy is xed to b e lazy then we call such

if it has a transformation whichiscomplete and complexity

a transformation lazycomplete

preserving 

Thus an hyp ercomplete transformation allows to cal

Functionally Mo ded programs as exp ected satises the

culate also nite approximations of the answer semantics

ab ove condition

allowing to fully reconstruct the answer semantics not only

Theorem The class of Functional ly Modedprograms

of terminating but also of nonterminating logic programs

is functional

The transformation here presented is not hyp ercom

plete It can however b e mo died to b e such essentially

Optimality

making all the functions parametric to store howmany an

swers have b een so far calculated and mo difying the equa

We will now show that the class of Functionall y Mo ded pro

tions using continuations techniques cf

grams can b e byright considered the functional core of logic

Being completeness implied byhyp ercompleteness the

programs since it cannot b e enlarged without losing func

existence of such a transformation for the class of Function

tionality In fact we will proveeven more Let us weaken

ally Mo ded programs makes p ossible to restate the analo

the notion of functional class this way

gous of the Optimality Theorem where functionality is re

placed by the stronger notion of hyp erfunctional ity replac

Denition A class of logic programs is hard ly func

ing completeness byhyp ercompleteness in Denition

tional if it has a transformation whichiscomplete and

FM is maximal among the hyp erfunctional classes of logic

there is a computable function F such that for every pro

programs

gram P and goal G

Using lazy reduction however makes things simpler In

C P G F C P G 

deed Theorem holds for nonterminating logic programs

as well Hence if a logic program P is run with a goal G b oth

Hence we allow the transformation to arbitrarily worsen

in FM of course yielding  G with

P k k

the runtime b ehaviour of the logic program only provided

then P G J t Jt Jt

k the worsening can b e expressed by a computable function F

x

Thus via lazy reduction one can extract one by one the an

for instance with F x a class of logic programs in

swers ikavoiding to calculate the inner nontermi

i

P could b e translated into one in EXPTIME

nating part corresp onding to

k

We can now state the following surprising result

This can b e formally expressed bysaying that is lazy

Theorem Optimality Every class of logic programs

complete itsucestotake B x x and for i

that properly contains the Functional ly Modedprograms is

B x Es s x

i

not hard ly functional

z

i times

Since by Theorem FM is also functional and func

tional implies hardly functional we obtain straightawaythe

where E is so dened

following corollary

E ssxJu J v w J u E sxJv w

Corollary The class of Functional ly Modedprograms

E sx Fail Fail

is maximal among the functional ones

E sJu J v w u

That is to saywe cannot improveontheFM class without

Of course this follows from a stronger result cf Theorem of

lo osing functionali ty even hardly functionality maximality among the hardly hyp erfunctional classes 

Innite Lists

Fail and via the Data not equation N reduces to D

As said usage of logic programming directly in functional

handler equation D nally gives Fail 

programming can b e extremely useful when lazy reduction

is used In this case b esides the usual advantages of using

logic programming when expressing relations it is added the

N not Fail

further p ower of expressing innite lists via logic programs

N not ujv Fail

with innite answers

N not Fail

As a simple example the innite list of naturals s

N not J v Fail

ss can b e expressed in a functional program just

N not J ujv w Fail

using the denition of natural numb er

N not J Failv not v

natural

N not J J u v w not J u J v w

naturalsX naturalX

where the mo ding is naturalout

Table The not equations

Normal Logic Programs

Integration of Languages

After having analyzed denite logic programming weex

tend the results previously obtained to normal logic pro

The transformation presented here is of obvious imp or

gramming that is allowing usage of negation As usual in

tance also in the integration of logic and functional pro

Prolog negated atoms are solved using the negation as

gramming cf for a survey since it allows to combine

nite failure pro cedure ie they succeed if and only if they

in a direct and clean way logic programming with functional

nitely fail see eg

programming

Since wehave already given the denition of functionally

The rst and simpler form of integration oered by the

mo ded for a denite goalclause we can give the denition of

transformation is to mix every functional language with the

Functionally Mo ded for a normal logic program only giving

functionally mo ded logic programs functional co de can b e

it for goal or clauses with at least one o ccurrence of the not

interleaved directly with such logic programming co de and

op erator

hence the programmer can decide to write a certain part

Denition A goal not ps t is functional ly moded if

of the program in functional or logic programming style ac

ps t is such A clause p t s p s t

n

cording to what paradigm suites b etter

not p s t p s t of a normal logic program is

k k k n n n

Another kind of integration is to allow external functions

functional ly moded if b oth p t s p s t

n

directly in the logic program this is also known as amal

p s t and p t s p s t p s t

k k k n k k k

gamation Muchwork has b een done on this topic like

p s t p s t are such A program is Func

k k k n n n

usage of residuation principles together with sophisticated

tional ly Moded if each its clause is such 

forms of incomplete equational unication eg Sunication

in and Punication in along with these studies

Example Supp ose p and q are b oth mo ded in out

also a concrete language GAPlog has b een implemented Then pX f Z q X Y not pY Z qY Z isFunc

cf

tionally Mo ded since b oth pX f Z q X Y pY Z and

All these approaches have to face many diculties b oth pX f Z q X Y qY Z are 

of theoretical and of practical implementative nature es

The transformation can b e extended to cop e with Func

sentially due to the fact that logic programming as a whole

tionally Mo ded normal logic programs with little mo di

is not functional as shown in this pap er

cations

Instead fo cusing only on the functional core of logic

First new equations dening the not are added see Ta

programming here found we can giveamuch simpler and

ble

cleaner solution to the amalgamation problem

Second every literal of the form not ps t that app ears

Call P the Functionall y Mo ded logic program and F

in a goal or a clause is viewed by the transformation like

the functional program to b e amalgamated We divide the

not ps that is the comp ound function not p has as in

function symb ols that can b e used in a logic program into

puts the old inputs of p but pro duces no output corresp ond

external and internal ones external symb ols can app ear

ingly to the fact that a successful negative literal pro duce

outside the logic program ie in F while internal symbols

no bindings

cannot

For instance px y not q x z ry z is seen as

The amalgamation condition for P and F is simply in

px y not q xry z

every clause p t s p s t p s t of P ex

n n n n

With these simple extensions all the results previously

ternal symb ols that are op erators in F cannot o ccur in t

proved only for denite programs generalize verbatim to nor

mal logic programs

Example As a simple example consider the follow

ing GAPlog program to compute the factorial using the

Example In order to briey illustrate the b ehaviour

external symb ols and interpreted as usual in the

of the not supp ose the usual splitapp end program is called

functional program to amalgamate

with the goal not append X Y a translates this

factorial

factorialXXY factorialXY

goal into the expression D not append a Analo

This program is Functionall y Mo ded taking factorial mo ded

gously to the reduction seen in Example this expression

in out and satises the amalgamation condition 

reduces to D not J aJa Fail that via the

prop osal instead is completely symmetrical since also the The amalgamation condition is completely natural in

functional program can b e extended using p ossibly negated view of the functional nature of the FM class indeed a

atoms since via they are just syntactic sugaring for func clause p t s is seen as a function denition for

n

tion calls p ie p t and so the unique restriction it should

satisfy is that no op erator ie no other dened function

can app ear in the pattern t Hence the amalgamation

Further Applications

condition for a logic program P and a functional program

F cf Sub F b ecomes simply the mo dule relation P

Using Beyond Functionally Mo ded

section

In this subsection weshowhow in some cases can b e useful

It should b e noted that amalgamated programs as de

also outside the scop e of Functionally Mo ded programs

ned in can also cop e with external predicate symbols

First when in the denition of Functionally Mo ded pro

that can b e used as b o olean tests However we can con

grams we drop the requirement that t must b e linear in

sider such apparent extra p ower just as syntactic sugar ev

aclause p t s p s t p s t the trans

n n n n

ery o ccurrence of external predicates ps can b e seen more

formation pro duces a functional program with p ossibly

prop erly as an o ccurrence of test ps where test is dened

nonlinear patterns This program is directly utilizabl e if

in the logic program by test true and b oth p and true

the target language supp orts them like for instance Mi

are external symb ols true is intended to b e interpreted as

randa Even if the language do es not supp ort nonlinear

usual in every reasonable functional language as the b o olean

patterns but supp ort guards and the equality test as it is

truth function

the case for a great deal of functional languages then it

can b e proved that the usual implementation of nonlinear

Example Consider the following program after

patterns via guards see eg Ch is safe In most

leqx

of cases b oth of these two alternatives do not signicantly

leqyx x leqyx

aect the execution time

The leq predicate is designed to b e the less than or equal

Second FM could b e extended by making use of program

to relation on naturals to b e called with its rst argument

transformation Supp ose to have a transformation T from

uninstantiated eg leqx would give as answers for

a class of logic programs into FM This transformation

x the naturals and

cannot b oth b e complexity preserving and retain the answer

In is an external predicate symb ol But as said

semantics by the Optimality Theorem Anyway one of

the ab ove program can b e seen as syntactic sugar for the

these two prop erties could b e relaxed and tested singularly

following one

on each program of using a sucient criterion If the test

leqx

is passed the program is functional and can b e transformed

leqyx testx leqyx

into an equivalent functional program using the comp ound

testtrue

transformation T

where now and true are all external symbols

An example of this metho d has b een given in where

it is dened a transformation C called conormal that trans interpreted as usual in the functional program to amalga

lates into FM a big class of normal logic programs eg mate

all Well Mo ded programs Def b elong to this class And in fact with mo ding leqout in and testin the

This program transformation is complexity preserving and ab ove program is Functionally Mo ded and satises the amal

preservation of the answer semantics is relaxed into preser gamation condition 

vation of the least Herbrand Mo del cf Also C is

comp ositional more precisely C P QC P CQ and

Let us summarize what are the dierences of our ap

mo dulepreserving TocheckwhenC preserves the answer

proach to the integration of logic and functional programs

semantics some global criteria are employed

with the others present in the literature

Finallywe remark that the program transformation tech

Being logic and functional programming dierent para

nique may b e also useful to study termination prop erties of

digms all their integrations have b een so far obtained by

logic programs see the next subsection

dening a new language that extends logic or functional

programming to cop e with these dierences

Termination

Here we follow just the opp osite way we dene a new

sublanguage that diminishes logic programming to drop

An interesting applicatio n of hyp ercomplete transformations

these dierences

is the study of termination prop erties of logic programs In

logic programming indeed the study of termination is a

On the one hand all the other approaches try to seize the

very hard problem already for universal termination and

whole expressivepower of logic programming On the other

existential termination is still an op en problem cf

hand they need to dene every time a new language not

only with theoretical problems semantics completeness ef

Ahyp ercomplete transformation can provide a mean

ciency etc but also with the practical problem of build

for studying a whole sp ectrum of termination prop erties the

ing a correct and p ossibly fast sp ecic implementation

only requirement is that the functions B can b e dened in

i

for the language Instead our approach do es not try to re

the functional language used with indeed this is the case

tain the full p ower of logic programming but do es not have

for the mo died wehinted at in Section Lets call

the aforementioned problems since via the transformation

def B this denition Then

i

we can rely on the existing implementation of the chosen

P universally terminates wrt G i

target functional language

def B P B G terminates

Also the amalgamation prop osed in all the pap ers cited

in this section is only oneway that is the logic program

P existentiall y terminates wrt G i

is extended via external functions but not vice versa Our

def B P B G terminates

Program Sicstus Prolog Clean Saving

Pkterminates wrt G i def B P B G

k k

Ackermann

terminates a program k terminates i its rst k an

Engineering

swers are dierentfrom

Fourcolors

Although we did not explicitly include in this pap er the

Quicksort

mo dications to make hyp ercomplete itself can b e very

Reverse

useful in view of the following result

Splitapp end

Theorem Let P and G berespectively a Functional ly

Table Benchmark Comparison with Sicstus Prolog

Modedprogram and goal then P terminates wrt G if and

only if P terminates wrt G

Despite of this in the b enchmarks wehave used the pure

Hence the techniques to prove termination of functional

co de describ ed by the transformation as presented in this

programs eg can b e used via also for Func

version of the pap er

tionally Mo ded logic programs

The languages employed are the commercial compiler

The ab ove theorem can also b e combined with program

Sicstus Prolog v cf and Concurrent Clean v

transformation if wehave a transformation T from a class

cf a public domain nonstrict functional language

of logic programs into FM that preserves nontermination

that can also b e used as a strict language on request

ie if P fGg do es not terminate then T P fT Gg

Wechose six dierent programs Ackermann from

do es not terminate as well then we can lo ok for sucient

pag is the usual Ackermann function Reverse is the

termination criteria of the programs in the whole class

list reversal pp Quicksort is the classical sort

simply analyzing their corresp onding functional programs

program after pag Splitapp end is the example

obtained via the comp osition of with T For instance

program seen in this pap er Example Fourcolors is a

the conormal transformation mentioned in Subsection

program byLPereira and A Porto to solve the four colors

preserves nontermination and hence it can b e used to study

map problem pp and Engineering is a plan

amuch bigger class than FM

ning problem for civil engineering after pp

It should b e noted that there are also other transforma

All the tests were executed using a Sparc Classic running

tional approaches to study termination of logic programs

SunOS C with Mbytes of RAM and a cache memory

eg the works of and where a logic program is

of Kbytes Like in timings are calculated taking the

translated into a term rewriting system Anyway those ap

b est value obtained out of ten runs

proaches are in principle less general than ours since they

Also the Sicstus Prolog compiler was not used with its

can cop e only with universal termination and cannot treat

default byte co de but with the fastco de option sp ecic for

negation

Sun architectures roughly three times faster than the de

fault and on the other hand no heap tuning cf was

made to improve Clean execution

Eciency

The results are presented in Table run times are ex

pressed in seconds Although of course the transforma

Wehave seen that b esides its use in the pro of of the

tion should b e tested with heavier applications we think

Optimality Theorem can haveavariety of applicatio ns In

the results give the avor that employing transformational

particular it can b e used to integrate Functionally Mo ded

techniques like that used here can b e pro ductive not only

logic programming directly in functional programming or

from a theoretical but also from a practical p oint of view

to amalgamate them as seen in Section In this section

we try to give some indications on how this approachisgood

not only in theory but also in practice

Acknowledgements

We will test the p ossible use of the transformation in

I wish to thank Krzysztof R Apt and Jan Willem Klop

conjunction with an existing implementation of a functional

Thanks also to the referees for some useful style hints

language like program compiler of Functionally Mo ded pro

grams comparing the eciency of the obtained co de with

the original Prolog one

References

It should b e remarked that the transformation we pre

J Andersson S Andersson K Bo ortz M Carlsson sented in this pap er has not b een sp ecically designed for an

H Nilsson J Widen and T Sjoland Sicstus prolog implementation but only for presentation purp oses Among

users manual SICS Technical Rep ort T Swedish the practicable improvements we mention

Institute of Computer Science

Simple and timegaining optimizations of are p ossi

AW App el Compiling with continuations Cambridge ble eg via a simple analysis many Datahandlers can

University Press b e removed

KR Apt and R Bol Logic programming and negation When it is known what reduction strategy is utilized

Asurvey Journal of Logic Programming further optimizations are p ossible for instance the

Datahandler equations schema can b e written in a

more ecientway

S Bonnier and J Maluszynski Towards a clean amal

gamation of logic programs with external pro cedures In The runtime b ehaviour can b e greatly improved mak

International ConferenceonLogic Programming pages ing use of features typical of the target language when

MIT Press Also in Pro c Intl Conf on this is known in advance eg guards

Algebraic and Logic Programming pages LNCS Springer

R Cartwright Recursive programs as denitions in rst EGJMH Nocker JEW Smetsers MCJD van

order logic SIAM Journal on Computing Eekelen and MJ Plasmeijer Concurrent Clean In

EHL Aarts J van Leeuwen and M Rem editors rd

Paral lel architectures and languages EuropePARLE

H Co elho and JC Cotta Prolog by ExampleSymb olic

volume of LNCS pages Springer

Computation Series SpringerVerlag

Verlag

J Darlington AJ Field and H Pull The unica

SL Peyton Jones The Implementation of Functional

tion of functional and logic languages In D DeG

Programming LanguagesInternational Series in Com

ro ot and G Lindstrom editors Logic Programming

puter Science PrenticeHall

Functions Relations and Equations pages En

glewo o d Clis New Jersey PrenticeHall R Plasmeijer and M van Eekelen Functional Pro

gramming and Paral lel Graph RewritingInternational

D de Schreye and S Decorte Termination of logic

Computer Science Series AddisonWesley

programs The neverending story Journal of Logic

Programming K Rao D Kapur and RK Shyamasundar A transfor

mational metho dology for proving termination of logic

P Dembinski and J Maluszynski ANDparallelism

programs In Proceedings of the Fifth Conferenceon

with intelligent backtracking for annotated logic pro

Computer ScienceLogicvolume of LNCS pages

grams In Proceedings of the International Symposium

Berlin SpringerVerlag

on Logic Programming pages Boston

US Reddy Transformation of logic programs into

N Dershowitz Termination of rewriting Journal of

functional programs In Proceedings of the Interna

Symbolic Computation

tional SymposiumofLogic Programming pages

IEEE February

S Feferman for termination and correctness of

functional programs In YN Moschovakis editor Logic

US Reddy On the relationships b etween logic and

from Computer Science Proceedings of a Workshop

functional programming In D DeGro ot and G Lind

held November pages Springer

strom editors Logic Programming Functions Rela

Verlag

tions and Equations pages PrenticeHall Engle

wo o d Clis New Jersey

M Hanus The integration of functions into logic pro

gramming From theory to practice Journal of Logic

L Sterling and E Shapiro The Art of PrologMIT

Programming

Press

PH Hartel and KG Langedo en Benchmarking imple

mentations of lazy functional languages In Proceedings

FPCA pages

A Kagedal and F Kluzniak Enriching Prolog with S

unication In J Darlington and R Dietrich editors

Workshop on Workshops in

Computing pages Springer

G Lindstrom J Maluszynski and T Ogi Our LIPS

are sealed Interfacing functional and logic program

ming systems In Proceedings of the th International

Symposium on Implementation

and Logic Programmingvolume of LNCS pages

Springer

JW Lloyd Foundations of Logic Programming

SpringerVerlag second edition

J Maluszynski S Bonnier J Boye F Kluzniak

A Kagedal and U Nilsson Logic programs with exter

nal pro cedures In K Apt J de Bakker and J Rutten

editors Logic Programming Languages Constraints

Functions and Objects pages MIT Press

M Marchiori Logic programs as term rewriting sys

tems In G Levi and M Ro drguezArtalejo edi

tors Proceedings of the Third International Conference

on Algebraic and Logic Programmingvolume of

LNCS pages SpringerVerlag

M Marchiori On safe transformation of logic programs

Draft Forthcoming as technical rep ort