Conference PaperPDF Available

An Automatic Composition Algorithm for Functional Logic Programs

Authors:

Abstract

Functional logic languages with a complete operational semantics are based on narrowing, which combines the instantiation of variables with the reduction of expressions. In this paper, we investigate the relationship between partial evaluation and more general transformations based on folding/unfolding. First, we show that the transformations obtained by partial evaluators can be also achieved by folding/unfolding using a particular kind of eurekas which can be mechanically attained. Then, we propose an algorithm (based on folding/unfolding) which starts with the automatic eureka generation and is able to perform program composition, i. e. it is able to produce a single function definition for some nested functions of the original program. This avoids the construction of intermediate data structures that are produced by the inner function and consumed as inputs by the outer function. As opposed to both partial evaluation and (general) fold/unfold transformations, strong correctness of the transformed programs holds w. r. t. goals which contain calls to the old function symbols—i. e. from the original program—as well as to the new ones—i. e. introduced during the transformation.
... This phase corresponds to the so-called eureka generation phase, which is the key point for a transformation strategy to proceed 3 . The problem of achieving an appropriate set of eureka de nitions is well-known in the literature related to fold/unfold transformations 10,20,22,4]. For the case of the composition strategy, eureka de nitions can be easily identi ed since they correspond to nested calls, although more re ned static analysis (like the one presented in 4], which is based on partial evaluation) may obtain optimal sets of eureka de nitions in one go. ...
... Moreover, since calls to old symbols are rede ned and solved by calls to the optimized definitions of new function symbols, our method guaranties gains in e ciency. By using our automatic tupling algorithm, programs with exponential complexities can be sometimes reduced to linear ones, which contrast with other automatic transformation strategies such as composition or partial evaluation, where optimizations never change the algorithmic complexity of a program ( 4]). ...
Article
This paper investigates the optimization by fold/unfold of functional-logic programs with operational semantics based on needed narrowing. Transformation sequences are guided by the tupling strategy, a powerful method that avoids multiple accesses to data structures and redundant sub-computations. We systematically decompose the internal structure of tupling in three low-level transformation phases in order to built a global automatic algorithm where eureka definitions are generated in an incremental way. The resulting strategy is (strongly) correct and complete, it avoids redundant transformation steps and it is elegant, realistic and applicable to most practical cases. Moreover and most important, our technique is specially well-suited for functional-logic programs since, in contrast with prior approaches for pure functional programs that may produce corrupt integrated programs, (forbidden) extra variables on rules are avoided and non overlapping rules are produced.
... Program transformations provide a methodology for deriving correct and possibly efficient programs. We recall first a simple transformation methodology based on fold/unfold techniques [12,13]. Then we recall the narrowing-driven partial evaluation, which was first proposed in [16] and is the first generic algorithm for the specialization of functional logic programs. ...
... An extension of the narrowing-based fold/unfold transformation framework of [12,13] to rewriting logic theories as implemented in the functional programming language Maude [29] can be found in [3]. It allows one to deal with (nondeterministic) rules, equations, sorts and algebraic laws (like commutativity and associativity). ...
Conference Paper
Full-text available
The Italian contribution to functional-logic programming has been significant and influential in a number of areas of semantics, and semantics-based program manipulation techniques. We survey selected topics, with a particular regard to debugging and transformation techniques. These results as usual depend on the narrowing strategy which is adopted and on the properties satisfied by the considered programs. In this paper, we restrict ourselves to first-order functional-logic languages without non-deterministic functions. We start by describing some basic classical transformation techniques, namely folding and unfolding. Then, we recall the narrowing-driven partial evaluation, which is the first generic algorithm for the specialization of functional logic programs. Regarding debugging, we describe a goal-independent approach to automatic diagnosis and correction which applies the immediate consequence operator modeling computed answers to the diagnosis of bugs in functional logic programs. A companion bug-correction program synthesis methodology is described that attempts to correct the erroneous components of the wrong code.
... In the following, we illustrate the power of our transformation system by tackling some representative examples regarding the optimizations of composition and tupling [13]. Both strategies have been recently automated for functional– logic programs in [3] and [25] respectively, and they can be easily adapted to functional programming by simple considering the instantiation rule we have just introduced in this paper. See also [1] for an implemented prototype that optimizes both pure functional programs and functional–logic programs. ...
Article
Full-text available
In this paper we show how to transfer some developments done in the field of functionallogic programming (FLP) to a pure functional setting (FP). More exactly, we propose a complete fold/unfold based transformation system for optimizing lazy functional programs. Our main contribution is the definition of a safe instantiation rule which is used to enable effective unfolding steps based on rewriting. Since instantiation has been traditionally considered problematic in FP, we take advantage of previous experiences in the more general setting of FLP where instantiation is naturally embedded into an unfolding rule based on narrowing. Inspired by the so called needed narrowing strategy, our instantiation rule inherits the best properties of this refinement of narrowing. Our proposal optimizes previous approaches (that require more transformation effort) defined in the specialized literature of pure FP by anticipating bindings on unifiers used to instantiate a given program rule and by generating redexes at different positions on instantiated rules in order to enable subsequent unfolding steps. As a consequence, our correct/complete technique avoids redundant rules and preserves the natural structure of programs.
... This phase 3 corresponds to the so-called eureka generation phase, which i s t h e key point for a transformation strategy to proceed. The problem of achieving an appropriate set of eureka deenitions is well-known in the literature related to fold/unfold transformations 10, 19, 21, 5] . For the case of the composition strategy , eureka deenitions can be easily identiied since they correspond to nested calls. ...
Conference Paper
This paper investigatesthe optimization by fold/unfold of functional-logic programswith operational semantics based on needed narrowing. Transformation sequences are automatically guided by tupling, a powerful strategy that avoids multiple accesses to data structures and redundant sub-computations. We systematically decompose in detail the internal structure of tupling in three low-level transformation phases (definition introduction, unfolding and abstraction with folding) that constitute the core of our automatic tupling algorithm. The resulting strategy is (strongly) correct and complete, efficient, elegant and realistic. In addition (and most important), our technique preserves the natural structure of multi-paradigm declarative programs, which contrasts with prior pure functional approachesthat produce corrupt integrated programswith (forbidden) overlapping rules.
... Nowadays, we are implementing our technique in order to show its effectiveness in practice. For the future we are also interested in defining more sophisticated and powerful transformation strategies, such as composition and tupling, as we have previously done in functional logic programming ([3,20,9]), but focusing now in the fuzzy field. In the limit, we also think that all these proposals allow a future adaptation to the fully integrated field of functional–fuzzy–logic programming, by considering languages such as the one we are nowadays designing in [23,24]. ...
Article
Full-text available
Multi-adjoint logic programming represents a very recent, extremely flexible attempt for introducing fuzzy logic into logic programming. Inspired by our previous experiences in the field of (declarative) program transformation, in this paper we propose the development of a fold/unfold based transformation system for optimizing such kind of fuzzy logic programs. The starting point is a set of unfolding-based transformations together with a reversible kind of fuzzy folding, that we have designed in the past. The present work substantially improves this last transformation operation by allowing the possibility of using rules belonging to dierent programs in a transformation sequence when performing a folding step, which is crucial to obtain better, recursive and elegant definitions of fuzzy predicates. In contrast with other declarative paradigms, in the fuzzy setting it is mandatory to pack sets of fuzzy predicates in tuples, if we really want the folding operation to proceed. This implies the need for re-defining the classical "definition introduction" transformation rule and introducing a completely new operation, that we call "aggregation", which is especially tailored for the new framework. Finally, we illustrate how the eects of appropriately applying our set of transformation rules (definition introduction, aggregation, folding, unfolding and facting) to a given program, are able to improve the execution of goals against transformed programs.
... However, the only framework of this kind in the literature is Alpuente et al. 2004) and their proofs of correctness-regarding the unfolding transformation-rely on the results in this article. The precise relation between partial evaluation and the fold/unfold transformation-for lazy functional logic programs-can be found in (Alpuente et al. 2000). ...
Article
Full-text available
Many functional logic languages are based on narrowing, a unification-based goal-solving mechanism which subsumes the reduction mechanism of functional languages and the resolution principle of logic languages. Needed narrowing is an optimal evaluation strategy which constitutes the basis of modern (narrowing-based) lazy functional logic languages. In this work, we present the fundamentals of partial evaluation in such languages. We provide correctness results for partial evaluation based on needed narrowing and show that the nice properties of this strategy are essential for the specialization process. In particular, the structure of the original program is preserved by partial evaluation and, thus, the same evaluation strategy can be applied for the execution of specialized programs. This is in contrast to other partial evaluation schemes for lazy functional logic programs which may change the program structure in a negative way. Recent proposals for the partial evaluation of declarative multi-paradigm programs use (some form of) needed narrowing to perform computations at partial evaluation time. Therefore, our results constitute the basis for the correctness of such partial evaluators.
Conference Paper
Full-text available
Multi-adjoint logic programming represents a very recent, extremely flexible attempt for introducing fuzzy logic into logic programming. Inspired by previous approaches largely used in other (crisp) declarative paradigms, in this paper we propose the development of a fold/unfold based transformation system for optimizing such kind of fuzzy logic programs. We prove that our set of transformation rules composed by definition introduction, folding, unfolding and facting, enjoys strong correctness properties (i.e. the semantics of computed substitutions and truth degrees is preserved) and it is able to significantly improve the execution of goals against transformed programs. To the best of our knowledge, this is the first approach to the construction of a complete transformation system in a fuzzy logic setting.
Conference Paper
This paper investigates the optimization by fold/unfold of declarative programs that integrate the best features from both functional and logic programming. Transformation sequences are guided by a mixed strategy which, in three low-level transformation phases, successfully combines two well-known heuristics -composition and tupling-, thus avoiding the construction of intermediate data structures and redundant sub-computations. In particular, whereas composition is able to produce a single function definition for some nested (composed) functions, the tupling method merges non-nested functions calls into a new function definition called eureka. We solve the non trivial problem of discovering the set of calls to be tupled in an incremental way, i.e. by chaining different eureka definitions where only non-nested calls sharing common variables are taken into account. Moreover, by appropriately combining both strategies, together with a simplification pre-process based on a kind of normalization, we automatically optimize a wide range of programs (with nested and/or non-nested function calls) at a very low cost.
Article
This paper abstracts the contents of a PhD dissertation entitled ‘Transformation Rules and Strategies for Functional-Logic Programs’ which has been recently defended. These techniques are based on fold/unfold transformations and they can be used to optimize integrated (functional-logic) programs for a wide class of applications. Experimental results shows that typical examples in the field of Artificial Intelligence are successfully enhanced by our transformation system SYNTH. The thesis presents the first approach of these methods for declarative languages that integrate the best features from functional and logic programming.
Article
Full-text available
La evaluación parcial dirigida por narrowing (NPE: Narrowing-driven Partial Evaluation) es una técnica potente para la especialización de sistemas de reescritura, i.e., para el componente de primer orden de muchos lenguajes declarativos (lógico) funcionales como Haskell, Curry o Toy. Los evaluadores parciales se clasifican en dos grandes categorías: online y offline, de acuerdo al momento temporal en que se consideran los aspectos de terminación del proceso de especialización. Los evaluadores parciales online son usualmente más precisos ya que tienen más información disponible. Los evaluadores parciales offline proceden comúnmente en dos etapas; la primera etapa procesa un programa (e.g., para identificar aquellas llamadas a función que se pueden desplegar sin riesgo de no terminación) e incluye anotaciones para guiar las computaciones parciales; entonces, una segunda etapa, la de evaluación parcial propiamente dicha, sólo tiene que obedecer las anotaciones y por tanto el especializador es mucho más rápido que en la aproximación online. En esta tesis se presenta un nuevo esquema de evaluación parcial dirigido por narrowing, más eficiente y que asegura la terminación siguiendo el estilo offline. Para ello, identificamos una caracterización de programas cuasi-terminantes a los que llamamos "no crecientes". En tales programas, las computaciones por narrowing necesario presentan sólo un conjunto finito de términos diferentes (módulo renombramiento de variables). La propiedad de la cuasi-terminación es importante toda vez que su presencia es regularmente una condición suficiente para la terminación del proceso de especialización. Sin embargo, la clase de programas cuasi-terminantes es muy restrictiva, por lo que introducimos un algoritmo que acepta programas inductivamente secuenciales---una clase mucho más amplia sobre la que está definido el narrowing necesario---y anota aquellas partes que violan la caracterización de programas no crecientes. Para procesar de mane
Conference Paper
Full-text available
We have recently defined a framework for narrowing-driven partial evaluation (NPE) of functional logic programs. This method is as powerful as partial deduction of logic programs and positive supercompilation of functional programs. Although it is possible to treat complex terms containing primitive functions (e.g. conjunctions or equations) in the NPE framework, its basic control mechanisms do not allow for effective polygenetic specialization of these complex expressions. We introduce a sophisticated unfolding rule endowed with a dynamic narrowing strategy which permits flexible scheduling of the elements (in conjunctions) which are reduced during specialization. We also present a novel abstraction operator which extends some partitioning techniques defined in the framework of conjunctive partial deduction. We provide experimental results obtained from an implementation using the INDY system which demonstrate that the control refinements produce better specializations.
Conference Paper
Full-text available
Needed narrowing is a complete operational principle for modern declarative languages which integrate the best features of (lazy) functional and logic programming. We define a transformation methodology for functional logic programs based on needed narrowing. We provide (strong) correctness results for the transformation system w.r.t. the set of computed values and answer substitutions and show that the prominent properties of needed narrowing -- namely, the optimality w.r.t. the length of derivations and the number of computed solutions -- carry over to the transformation process and the transformed programs. We illustrate the power of the system by taking on in our setting two well-known transformation strategies (composition and tupling). We also provide an implementation of the transformation system which, by means of some experimental results, highlights the benefits of our approach.
Conference Paper
Full-text available
Functional logic languages combine the operational principles of the most important declarative programming paradigms, namely functional and logic programming. Inductively sequential programs admit the definition of optimal computation strategies and are the basis of several recent (lazy) functional logic languages. In this paper, we define a partial evaluator for inductively sequential functional logic programs. We prove strong correctness of this partial evaluator and show that the nice properties of inductively sequential programs carry over to the specialization process and the specialized programs. In particular, the structure of the programs is preserved by the specialization process. This is in contrast to other partial evaluation methods for functional logic programs which can destroy the original program structure. Finally, we present some experiments which highlight the practical advantages of our approach.
Article
In this tutorial the specialisation of declarative logic pro-grams is presented. The main correctness results are given, and the outline of a basic algorithm for partial evaluation of a logic program with respect to a goal. The practical considerations of gaining efficiency (and not losing any) are discussed. A renaming scheme for performing structure spe-cialisation is then described, and illustrated on a well-known string matching example. The basic algorithm is enhanced by incorporating abstract interpretation. A two-phase spe-cialisation is then described and illustrated, in which partial evaluation is followed by the detection and removal of use-less clauses. This is shown for the specialisation of a proof procedure for first order logic. The specialisation of meta programs is very important in logic programming, and the ground representation for object programs has to be han-dled. Some techniques for doing this are described. Compar-isons are made in the tutorial to similar work in other pro-gramming languages, and the similarities and differences be-tween them and logic program specialisation is discussed.
Article
This paper gives a theoretical foundation for partial evaluation in logic programming. Let P be a normal program, G a normal goal, A a finite set of atoms, and P′ a partial evaluation of P wrt A. We study, for both the declarative and procedural semantics, conditions under which P′ is sound and complete wrt P for the goal G. We identify two relevant conditions, those of closedness and independence. For the procedural semantics, we show that, if P′ ∪ {G} is A-closed and A is independent, then P′ is sound and complete wrt P for the goal G. For the declarative semantics, we show that, if P′ ∪ {G} is A-closed, then P′ is sound wrt P for the goal G. However, we show that, unless strong conditions are imposed, we do not have completeness for the declarative semantics. A practical consequence of our results is that partial evaluators should enforce the closedness and independence conditions.
Article
An algorithm that transforms programs to eliminate intermediate trees is presented. The algorithm applies to any term containing only functions with definitions in a given syntactic form, and is suitable for incorporation in an optimizing compiler.