27 research outputs found

    Deriving animations from recursive definitions

    Get PDF
    This paper describes a generic method to derive an animation from a recursive definition, with the objective of debugging and understanding this definition by expliciting its control structure. This method is based on a well known algorithm of factorizing a recursive function into the composition of the producer and the consumer of its call tree. We developed a systematic method to transform both the resulting functions in order to draw the tree step by step. The theory of data types as fixed points of functors, generic recursion patterns, and monads, are fundamental to our work and are brie y presented. Using polytypic implementations of monadic recursion patterns and an application to manipulate and generate graph layouts we developed a prototype that, given a recursive function written in a subset of Haskell, returns a function whose execution yields the desired animation

    Program Calculation Properties of Continuous Algebras

    Get PDF
    Defining data types as initial algebras, or dually as final co-algebras, is beneficial, if not indispensible, for an algebraic calculus for program construction, in view of the nice equational properties that then become available. It is not hard to render finite lists as an initial algebra and, dually, infinite lists as a final co-algebra. However, this would mean that there are two distinct data types for lists, and then a program that is applicable to both finite and infinite lists is not possible, and arbitrary recursive definitions are not allowed. We prove the existence of algebras that are both initial in one category of algebras and final in the closely related category of co-algebras, and for which arbitrary (continuous) fixed point definitions ("recursion") do have a solution. Thus there is a single data type that comprises both the finite and the infinite lists. The price to be paid, however, is that partiality (of functions and values) is unavoidable. \ud We derive, for any such data type, various laws that are useful for an algebraic calculus of programs

    Point-free program calculation

    Get PDF
    Tese de doutoramento em Informática, ramo de Fundamentos da ComputaçãoDue to referential transparency, functional programming is particularly appropriate for equational reasoning. In this thesis we reason about functional programs by calculation, using a program calculus built upon two basic ingredients. The first is a set of recursion patterns that allow us to define recursive functions implicitly. These are encoded as higher-order operators that encapsulate typical forms of recursion, such as the well-known foldr operator on lists. The second is a point-free style of programming in which programs are expressed as combinations of simpler functions, without ever mentioning their arguments. The basic combinators are derived from standard categorical constructions, and are characterized by a rich set of equational laws. In order to be able to apply this calculational methodology to real lazy functional programming languages, a concrete category of partial functions and elements is used. While recursion patterns are already well accepted and a lot of research has been carried out on this topic, the same cannot be said about point-free programming. This thesis addresses precisely this component of the calculus. One of the contributions is a mechanism to translate classic pointwise code into the point-free style. This mechanism can be applied to a λ-calculus rich enough to represent the core functionality of a real functional programming language. A library that enables programming in a pure pointfree style within Haskell is also presented. This library is useful for understanding the expressions resulting from the above translation, since it allows their direct execution and, where applicable, the graphical visualization of recursion trees. Another contribution of the thesis is a framework for performing point-free calculations with higher-order functions. This framework is based on the internalization of some basic combinators, and considerably shortens calculations in this setting. In order to assess the viability of mechanizing calculations, several issues are discussed concerning the decidability of equality and the implementation of fusion laws.Devido à transparência referencial, o paradigma funcional é particularmente adequado ao raciocínio equacional. Nesta tese a manipulação de programas funcionais será feita por cálculo, sendo o cálculo de programas constituído por dois ingredientes fundamentais. O primeiro é um conjunto de padrões de recursividade que nos permite definir funções recursivas implicitamente. Estes padrões são codificados como operadores de ordem superior que ecapsulam formas de recursão típicas, tal como o bem conhecido operador foldr para listas. O segundo ingrediente é um estilo de programação “pointfree”, no qual os programas são definidos por combinação de funções mais simples sem nunca mencionar explicitamente os seus argumentos. Os combinadores fundamentais são derivados de construções categoriais padrão, e são caracterizados por um conjunto expressivo de leis equacionais. Para ser possível aplicar este método de cálculo a linguagens de programação funcional “lazy”, foi usada uma categoria concreta onde as funções e os elementos podem ser parciais. Ao contrário dos padrões de recursividade, que já são bem aceites e sobre os quais já se fez muita investigação, o mesmo não se pode dizer sobre a programação “point-free”. Esta tese aborda precisamente este componente do cálculo. Uma das contribuições é um mecanismo que permite traduzir código “pointwise” clássico para o estilo “point-free”. Este mecanismo pode ser aplicado a um λ-calculus suficientemente expressivo para representar a funcionalidade básica de uma linguagem de programação funcional real. Também se apresenta uma biblioteca que permite programar num estilo “point-free” puro dentro da linguagem Hankell. Esta biblioteca é útil para compreender as expressões que resultam da tradução acima referida, pois permite a sua execução directa e, quando aplicável, a visualização gráfica de árvores de recursividade. Outra contribuição da tese consiste numa metodologia para realizar cálculos “point-free” sobre funções de ordem superior. Esta metodologia é baseada na internalização de alguns combinadores fundamentais, e permite encurtar significativamente os cálculos. Para estabelecer a viabilidade de mecanização, também se discutem várias questões relacionadas com a decidibilidade da igualdade e a implementação de leis de fusão

    Point-free program transformation

    Get PDF
    Functional programs are particularly well suited to formal manipulation by equational reasoning. In particular, it is straightforward to use calculational methods for program transformation. Well-known transformation techniques, like tupling or the introduction of accumulating parameters, can be implemented using calculation through the use of the fusion (or promotion) strategy. In this paper we revisit this transformation method, but, unlike most of the previous work on this subject, we adhere to a pure point-free calculus that emphasizes the advantages of equational reasoning. We focus on the accumulation strategy initially proposed by Bird, where the transformed programs are seen as higher-order folds calculated systematically from a specification. The machinery of the calculus is expanded with higher-order point-free operators that simplify the calculations. A substantial number of examples (both classic and new) are fully developed, and we introduce several shortcut optimization rules that capture typical transformation patterns.Presidência do Conselho de Ministros - POSI/ICHS/44304/2002

    Law and Order in Algorithmics

    Get PDF
    An algorithm is the input-output effect of a computer program; mathematically, the notion of algorithm comes close to the notion of function. Just as arithmetic is the theory and practice of calculating with numbers, so is ALGORITHMICS the theory and practice of calculating with algorithms. Just as a law in arithmetic is an equation between numbers, like a(b+c) = ab + ac, so is a LAW in algorithmics an equation between algorithms. The goal of the research done is: (extending algorithmics by) the systematic detection and use of laws for algorithms. To this end category theory (a branch of mathematics) is used to formalise the notion of algorithm, and to formally prove theorems and laws about algorithms.\ud \ud The underlying motivation for the research is the conviction that algorithmics may be of help in the construction of computer programs, just as arithmetic is of help in solving numeric problems. In particular, algorithmics provides the means to derive computer programs by calculation, from a given specification of the input-output effect.\ud \ud In Chapter 2 the systematic detection and use of laws is applied to category theory itself. The result is a way to conduct and present proofs in category theory, that is an alternative to the conventional way (diagram chasing).\ud \ud In Chapter 3--4 several laws are formally derived in a systematic fashion. These laws facilitate to calculate with those algorithms that are defined by induction on their input, or on their output. Technically, initial algebras and terminal co-algebras play an crucial role here.\ud \ud In Chapter 5 a category theoretic formalisation of the notion of law itself is derived and investigated. This result provides a tool to formulate and prove theorems about laws-in-general, and, more specifically, about equationally specified datatypes.\ud \ud Finally, in Chapter 6 laws are derived for arbitrary recursive algorithms. Here the notion of ORDER plays a crucial role. The results are relevant for current functional programming languages

    Implementing Data-Flow Fusion DSL on Clojure

    Get PDF
    This paper presents a new optimization tech-nique for programming language Clojure based on the stan-dard fusion technique that merges list operations into a simplified loop.Short-cut fusions, foldr/build fusion, and stream fusions are standard fusion techniques used in a functional programming.Moreover, a recent fusion technique proposed by Lippmeier. Data flow fusion [7] can fuse loops containing several data consumers over stream operators on Haskell. However, this isonly for Haskell. Clojure\u27s transducers [2] are factory func-tions generating abstract list objects. The functions generated by them wait evaluation as a lazy evaluation partially.We introduce data-flow fusion macros into Clojure as a dynamic typing mechanism and show the difference of data flow fusion between that of Clojure and Haskell.We focus on Clojure which is a functional programming language with attracting features of dynamic typing, Lisp macros, partial lazy evaluation, and running on the Java Virtual Machine (JVM). Our macro compiles S-expression of Clojure to Clojure code and Java class file. Our ideas are implemented as a domain specific language, which has strong points of the pro-vision of a simple interface for loop fusion, and independence from the implementation of a Clojure Compiler.We discuss the advantages and disadvantages of data-flow fusion macro from experimental results and adaptability of our macro

    A shortcut fusion rule for circular program calculation

    Get PDF
    Circular programs are a powerful technique to express multiple traversal algorithms as a single traversal function in a lazy setting. In this paper, we present a shortcut deforestation technique to calculate circular programs. The technique we propose takes as input the composition of two functions, such that the first builds an intermediate structure and some additional context information which are then processed by the second one, to produce the final result. Our transformation into circular programs achieves intermediate structure deforestation and multiple traversal elimination. Furthermore, the calculated programs preserve the termination properties of the original ones

    Java stream optimization through program fusion

    Get PDF
    Dissertação de mestrado integrado em Computer ScienceCombining different programs or code fragments is a natural way to build larger programs. This allows programmers to better separate a complex problem into simple parts. Furthermore, by writing programs in a modular way, we increase code reusability. However, these simple parts need to be connected somehow. These connections are done via intermediate structures that communicate results between the different components, harming performance because of the overhead introduced by the allocation and deallocation of multiple structures. Fusion, a very commonly used technique in functional programming, aims to remove the creation of these unnecessary structures, as they don’t take part in the final result. With the introduction of streams and lambda expressions, Java made its way into a more functional programming style. Yet, these mechanisms lack optimization and the adaptation of fusion techniques used by some compilers for functional languages could benefit the performance of Java streams. In this thesis, we study how functional fusion can be adapted to Java Streams.Combinar diferentes programas ou fragmentos de código é uma forma natural de construir programas maiores. Isto permite aos programadores melhor separar um problema complexo em partes simples. Além disso, ao escrever programas de forma modular, estamos a aumentar a reutilização do código. Contudo, estas partes têm de ser ligadas de alguma maneira. Estas conexões são feitas via estruturas intermédias que comunicam os resultados entre os diferentes componentes, prejudicando a performance com o overhead introduzido pela alocação e desalocação de várias estruturas. A fusão, uma técnica muito usada em programação funcional, pretende remover a criação destas estruturas desnecessárias, uma vez que não tomam parte no resultado final. Com a introdução de streams e expressões lambda, o Java abriu caminho para um estilo de programação mais funcional. Mesmo assim, estes mecanismos não possuem otimização e a adaptação de técnicas de fusão utilizadas por alguns compiladores de linguagens funcionais poderiam beneficiar a performance das streams do Java. Nesta dissertação, é estudado como a fusão em programação funcional pode ser adaptada às streams do Java.This work is funded by ERDF - European Regional Development Fund through the Operational Programme for Competitiveness and Internationalisation – COMPETE 2020 Programme and by National Funds through the FCT - Foundation for Science and Technology within the project FCOMP-01-0124-FEDER-020484 and grant ref. BI2-2017_PTDC/EEI-ESS/5341/2014_UMINHO

    Hfusion : a fusion tool based on acid rain plus extensions

    Get PDF
    When constructing programs, it is a usual practice to compose algorithms that solve simpler problems to solve a more complex one. This principle adapts so well to software development because it provides a structure to understand, design, reuse and test programs. In functional languages, algorithms are usually connected through the use of intermediate data structures, which carry the data from one algorithm to another one. The data structures impose a load on the algorithms to allocate, traverse and deallocate them. To alleviate this ine ciency, automatic program transformations have been studied, which produce equivalent programs that make less use of intermediate data structures. We present a set of automatic program transformation techniques based on algebraic laws known as Acid Rain. These techniques allow to remove intermediate data structures in programs containing primitive recursive functions, mutually recursive functions and functions with multiple recursive arguments. We also provide an experimental implementation of our techniques which allows their application on user supplied programs

    Shortcut fusion rules for the derivation of circular and higher-order programs

    Get PDF
    Functional programs often combine separate parts using intermediate data structures for communicating results. Programs so defined are modular, easier to understand and maintain, but suffer from inefficiencies due to the generation of those gluing data structures. To eliminate such redundant data structures, some program transformation techniques have been proposed. One such technique is shortcut fusion, and has been studied in the context of both pure and monadic functional programs. In this paper, we study several shortcut fusion extensions, so that, alternatively, circular or higher-order programs are derived. These extensions are also provided for effect-free programs and monadic ones. Our work results in a set of generic calculation rules, that are widely applicable, and whose correctness is formally established.Fundação para a Ciência e a Tecnologi
    corecore