Rewinding Functions Through CPS∗ an Experience Report

Rewinding Functions Through CPS∗ an Experience Report

Rewinding functions through CPS∗ An experience report Marco Giunti NOVA LINCS, Universidade NOVA de Lisboa Portugal ABSTRACT functional programming in high level education, and support for The ability to rewind or step back computations is fundamental the functional software development in the day-to-day practice. in many functional programming approaches, which include the This experience report aims at presenting a contribution towards teaching of foundational computing courses, by allowing step-wise these directions by introducing a programming pearl that shows execution of algorithms, and the debugging of functional appli- how to offer support for tracing functionalities in continuation- cations, by permitting the inspection of the intermediate values passing style (CPS) programming (c.f. [1–3, 10]). We believe that of recursive computations. In this report, we present a functional this is relevant for the aforementioned objectives: from the point of programming pearl that shows how this can be accomplished in view of education, support for tracing in CPS may allow students continuation-passing style (CPS) by tracing the argument and the to better understand the behaviour of algorithms by stepping back continuation of each recursive call. To obtain maximum general- and forward the execution: this will be experimented in the context ity, the mechanism is provided by means of a monad transformer of the project FACTOR (http://ctp.di.fct.unl.pt/FACTOR), where tools that adds trace functionalities to arbitrary monads. We show ap- based on the construction presented in this paper will support plications of the transformation involving algebraic types, data the teaching of formal languages as automata and logics; from structures, references, and exceptions, and conclude by presenting the point of view of the daily routine of a developer, these added a functor that provides support for the automatic generation of CPS functionalities may be of help in the debugging of programs by functions with rewind functionalities. providing a general solution to the tracking of CPS calls. To illustrate, let us consider the problem of debugging a CPS ACM Reference Format: variant of the Fibonacci function in OCaml, that is fib : int -> Marco Giunti. 2019. Rewinding functions through CPS: An experience report. (int -> int) -> int. The two main (native) debugging tools avail- In Proceedings of the 21th International Symposium on Principles and Practice able are ocamltop’s trace, and ocamldebug; however, both of them of Declarative Programming, Porto, Portugal, October 07 - 09, 2019. ACM, New fib 6 (fun York, NY, USA, 7 pages. https://doi.org/10.1145/nnnnnnn.nnnnnnn offer poor support for CPS. For instance, the tracing of x -> x) in ocamltop produces 100 lines: the first 75 lines contain a sequence of entries of the form <-- n, fib --> <fun>, fib* 1 INTRODUCTION <-- <fun> where 0 ≤ n ≤ 6; the remaining 25 lines replicate the In recent years, the functional programming paradigm has became entry fib* --> 13. From this information, we can only infer the an hot topic among developers, largely because of the the indus- sequence of arguments n evaluated in the call’s tree, and the final try’s support for functional features in mainstream programming value: that is, the information embedded in the CPS continuation is languages, being Oracle’s introduction of lambda expressions in lost. To better analyse the behaviour of CPS evaluation, we may be Java 8 the most notable example. Still, the most part of developers interested in applying the continuations to their argument in each seem to be reluctant to adopt the functional style of programming step of the evaluation, thus providing support for some form of re- in their projects: this is matter of a long-standing debate in the pro- verse engineering based on the values produced in the intermediate gramming language community and in academia, where functional evaluation steps. programming historically has a strong support. Without entering In this report, we present a general solution to this problem by into the debate, we identify at least two aspects that we believe providing a monad transformer that adds trace and rewind func- relevant to the diffusion of the functional programming paradigm tionalities to arbitrary monads. The Log-Rewind monad transformer among developers: best practices of teaching formal models and provides a general framework to analyse the step-by-step execution of CPS transformations by allowing to record the pair of arguments ∗This work was partially supported by the Tezos foundation through a grant for the (n, f) passed in each call, where n has type ’a, and f is a function project “FACTOR - A Functional Programming Approach to Teaching Portuguese ’a (’a, ’b) n : ’a Foundational Computing Courses”. from to a monad with parametric type : that is, and f : ’a -> (’a, ’b) mon. For instance, the execution of a variant Permission to make digital or hard copies of all or part of this work for personal or of fib that uses a transformation of the State monad by passing the classroom use is granted without fee provided that copies are not made or distributed argument 6, and an “ identity” monadic function as continuation, for profit or commercial advantage and that copies bear this notice and the full citation generates a log that allows to produce a sequence of 25 pairs of the on the first page. Copyrights for components of this work owned by others than ACM must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, form (n, f n); an excerpt of this sequence is (pretty-print): (6, 6), to post on servers or to redistribute to lists, requires prior specific permission and/or a (5, 10), (4, 12), (3, 13), ... , (0, 12), ... , (2, 13), (1, 13), ... , (0, 12). fee. Request permissions from [email protected]. We further increase the support to the software development PPDP 2019, 7-9 October 2019, Porto, Portugal © 2019 Association for Computing Machinery. process by introducing a functor that allows to automatically gen- ACM ISBN 978-x-xxxx-xxxx-x/YY/MM...$15.00 erate the code for Log-Rewind CPS functions. The monadic variant https://doi.org/10.1145/nnnnnnn.nnnnnnn PPDP 2019, 7-9 October 2019, Porto, Portugal Giunti of fib is generated by abstracting the structure of the recursion Table 1: Log-Rewind monad transformer by means of algebraic constructors for binary and unary functions, and self-calls, as illustrated by the list below 1: 1 module type MONAD = sig 2 type 'a mon [(Binary (+),( fun n ->n-1), Self); 3 type 'a result= 'a (Unary (fun n ->n),( fun n ->n-2), Self)] 4 val ret: 'a -> 'a mon 5 val bind: 'a mon ->( 'a -> 'b mon) -> 'b mon Contribution. We present a functional programming pearl that 6 val run: 'a mon -> 'a result 7 end shows how to add trace and rewind functionalities to CPS func- 8 (* Monad transformer : adding Log-Rewind to monad M *) 9 (* Log contains pairs of (argument, function) where *) tions. The mechanism is deployed by means of a monad transformer 10 (* function receives argument and returns a monad *) that adds trace, forward, and backward values to arbitrary monads. 11 module LogRwdTransf(M : MONAD)= struct 12 type ('a, 'b) log=( 'a, 'b) argFunPair list We analyse some application of our construction, and conclude by 13 and ('a, 'b) mon=( 'a, 'b) log ->( 'a*( 'a, 'b) log) M.mon presenting a functor that allows to automatically generate CPS func- 14 and ('a, 'b) argFunPair=( 'a*( 'a ->( 'a, 'b) mon)) 15 type ('a, 'b) result=( 'a*( 'a, 'b) log) M.result tions with support for log and rewind from the abstract structure 16 let ret x= fun l -> M.ret(x,l) of the idealized function. 17 let bind m f= fun l -> M.bind(m l)( fun (x,s ') ->fxs ') 18 let (>>=)= bind 19 let lift m= fun l -> M.bind m( fun x -> M.ret(x,l)) Related Work. The use of a replay monad to trace intermediate 20 let run(m:( 'a, 'b) mon):( 'a, 'b) result= computations is not new, e.g. [4, 9, 11]; however, to the best of our 21 M.run( M.bind(m[])( fun (x,l) -> M.ret(x, List.rev l))) 22 let log(p:( 'a, 'b) argFunPair)= fun l -> M.ret((),p::l) knowledge, this is the first attempt to devise a general mechanism 23 let sizeOfLog(s:( 'a, 'b) result)= match s with _,l -> List.length l 24 let nthFunPair(s:( 'a, 'b) result)(n: int)= match s with _,l -> to add tracing functionalities to CPS functions. Log-based replay 25 if n<0 ||n >= sizeOfLog s then List.nth l0 else List.nth l n has been used in Haskell to implement server-side web scripting 26 let navigate(s:( 'a, 'b) result)(n: int)= 27 match nthFunPair s n with x,f -> through CGI [11]. In that framework, a CGI monad (implemented 28 match run(f x) with r,_ ->s,r,n on top of the IO monad) mediates the interaction with the envi- 29 let backward(s:( 'a, 'b) result)(n: int)= 30 let k= sizeOfLog s ronment by means of functions tell and ask, and relies on a log 31 in navigate s( if n<0 ||n>k then k-1 else n-1) containing all interactions of the server with the client page to 32 let forward(s:( 'a, 'b) result)(n: int)= 33 let k= sizeOfLog s invoke the callback actions included in a ask invocation. A monad 34 in navigate s( if n<0 ||n>k then 0 else n+1) transformer is used in [9] to accumulate observations about execu- 35 end tion as an effect. An observation is a monadic value mark, that can be interpreted as a tick; this increase the flexibility of the approach by deferring the instantiation of the observation to the transformation.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    7 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us