Handlers in Action. Ohad Kammar<ohad.kammar@cl.cam.ac.uk>



Similar documents
Handlers in Action. Ohad Kammar. Sam Lindley. Nicolas Oury. Abstract. 1. Introduction. University of Cambridge

Unboxed Polymorphic Objects for Functional Numerical Programming

Extensible Effects An Alternative to Monad Transformers

Programming and Reasoning with Algebraic Effects and Dependent Types


Chapter 15 Functional Programming Languages

The countdown problem

Factorizations: Searching for Factor Strings

Syllabus for CS 134 Java Programming

Chapter 7: Functional Programming Languages

Cross-platform Compilers for Functional Languages


Idris, a General Purpose Dependently Typed Programming Language: Design and Implementation

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals

Programming and Reasoning with Side-Effects in IDRIS

Parametric Domain-theoretic models of Linear Abadi & Plotkin Logic

CSE 307: Principles of Programming Languages

Cobol. By: Steven Conner. COBOL, COmmon Business Oriented Language, one of the. oldest programming languages, was designed in the last six

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

Chapter 2: Elements of Java

A tutorial on the universality and expressiveness of fold

Fundamentals of Java Programming

Negative Binomial. Paul Johnson and Andrea Vieux. June 10, 2013

1998. (R. Bird and P. Wadler, Introduction to Functional Programming, Prentice

Programming Language Rankings. Lecture 15: Type Inference, polymorphism & Type Classes. Top Combined. Tiobe Index. CSC 131! Fall, 2014!

Programming Language Pragmatics

Regular Expressions with Nested Levels of Back Referencing Form a Hierarchy

UNIVERSITY OF LONDON (University College London) M.Sc. DEGREE 1998 COMPUTER SCIENCE D16: FUNCTIONAL PROGRAMMING. Answer THREE Questions.

Tutorial on Writing Modular Programs in Scala

The full setup includes the server itself, the server control panel, Firebird Database Server, and three sample applications with source code.

El Dorado Union High School District Educational Services

Building GUIs in Haskell

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Fun with Phantom Types

Testing and Tracing Lazy Functional Programs using QuickCheck and Hat

OutsideIn(X) Modular type inference with local assumptions

Anatomy of Programming Languages. William R. Cook

Introduction to type systems

Compiling Recursion to Reconfigurable Hardware using CLaSH

Advanced Functional Programming (9) Domain Specific Embedded Languages

6.170 Tutorial 3 - Ruby Basics

Introduction to Programming with Xojo

Object-Oriented Software Specification in Programming Language Design and Implementation

10CS35: Data Structures Using C

Lecture 12: Abstract data types

Type Classes with Functional Dependencies

Habanero Extreme Scale Software Research Project

Applets, RMI, JDBC Exam Review

BUSINESS RULES CONCEPTS... 2 BUSINESS RULE ENGINE ARCHITECTURE By using the RETE Algorithm Benefits of RETE Algorithm...

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

Course MS10975A Introduction to Programming. Length: 5 Days

Math 461 Fall 2006 Test 2 Solutions

Regular Expressions and Automata using Haskell

CEC225 COURSE COMPACT

Oracle Database: SQL and PL/SQL Fundamentals NEW

RSA and Primality Testing

Course Title: Software Development

CS 111 Classes I 1. Software Organization View to this point:

VLOOKUP Functions How do I?

1 Digital Signatures. 1.1 The RSA Function: The eth Power Map on Z n. Crypto: Primitives and Protocols Lecture 6.

ENGI E1112 Departmental Project Report: Computer Science/Computer Engineering

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

ML for the Working Programmer

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Dialog planning in VoiceXML

Introduction to Matlab

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

Microsoft Publisher 2010 What s New!

Towards Interface Types for Haskell

Practical Generic Programming with OCaml

Chapter 3 RANDOM VARIATE GENERATION

ZQL. a cryptographic compiler for processing private data. George Danezis. Joint work with Cédric Fournet, Markulf Kohlweiss, Zhengqin Luo


Graphing Quadratic Functions


The Technology Behind a Graphical User Interface for an Equational Reasoning Assistant

Polymorphic Type Inference and Abstract Data Types

Exponential Distribution

Ergonomic solutions in tomato harvesting and postharvest

This course provides students with the knowledge and skills to develop ASP.NET MVC 4 web applications.

Java (12 Weeks) Introduction to Java Programming Language

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

DICOM Correction Item

Coeffects: Unified static analysis of context-dependence

MICROSOFT EXCEL FORMULAS

Database Programming with PL/SQL: Learning Objectives

Domains and Competencies

Constrained optimization.

Verified Networking using Dependent Types

Geometric Camera Parameters

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved.

Transcription:

Ohad Kammar <ohad.kammar@cl.cam.ac.uk> Higher-Order Programming and Effects (HOPE) September 8, 2012 joint with Sam Lindley and Nicolas Oury Isaac Newton Trust Computer Laboratory

Exception handlers handle if (get ) =0 then raise DivideByZero else 42 / (get ) with DivideByZero 0 e raise e return x display x

Effect handlers handle if (get ) =0 then raise DivideByZero else 42 / (get ) with raise DivideByZero k 0 raise e k raise e get l k k (1) return x display x

Addressed questions What? What are effect handlers? Why? What are they good for? Again? Haven t I already seen them?

Contribution functional language with handlers sound typeand-effect system What? execution model: small-step SOS Why? handler-oriented programming: handler libraries Again? comparison: Filinski s monadic reflection Two implementation techniques: free monads in Haskell; (delimited) control operators in SML and Racket; Goal Facilitate operational discussion.

What? execution model

Algebraic effects Operations, parameter types, arities op : Pa Ar For example: lookup : Loc Integer update :(Loc, Integer) Unit raise : Exception Empty Usage op V (λx M) For example: lookup (λi update (, i + 1) (λ ())

Algebraic effects (cntd.) Generic effects Another familiar variant: gen V = op V (λx x) For example: get = lookup (λi i) set (, i) =update (, i) (λ ()) raise e = raise e (λz whatever z)

λ eff -calculus Syntax Value terms V Computation terms Handlers For example: M ::=... op V (λx M) handle M with H H ::= op pk M... return x N raise DivideByZero k 0 raise e k raise e lookup l k k (1) return x display x

λ eff -calculus Reduction rules handle if (get ) =0 then raise DivideByZero else 42 / (get ) with raise DivideByZero k 0 raise e k raise e lookup lk k (1) return x display x

λ eff -calculus Reduction rules handle if (lookup (λi i)) = 0 then M 1 else M 2 with H

λ eff -calculus Reduction rules handle if (lookup (λi i)) = 0 then M 1 else M 2 with H More generally: hoist handle lookup (λi if i = 0 then M 1 else M 2 ) with H H[op V (λx M)] hoist op V (λx H[M]) for hoisting frames H[ ] with x/ FV (H).

λ eff -calculus Reduction rules (cntd.) handle lookup (λi if i = 0 then M 1 else M 2 ) with... lookup lk k (1) op (λi handle if i = 0 then M 1 else M 2 with H )(1) More generally, for handler H satisfying x / FV (H): handle op V (λx M) with... op pk N... op N[V /p, (λx handle M with H)/k]

λ eff -calculus Reduction rules (cntd.) (λi handle if i = 0 then M 1 else M 2 with H )(1) β handle M 2 with H

λ eff -calculus Reduction rules (cntd.) handle 42 / (get ) with H hoist, op, β, arithmetic handle 42 with H

λ eff -calculus Reduction rules (cntd.) handle 42 with handler return... display 42 return x display x More generally: handle V with... return x N handler return N [V / x ]

λ eff -calculus Type-and-effect system Value types A, B ::=... U E C. Computation types C. Effect signatures: (with Pa and Ar value types) E ::= {op : Pa Ar,...} Handlers R ::= A E E C

λ eff -calculus Type-and-effect system (cntd.) Value type judgements Γ V : C. Computation type judgements Γ E M : C: Γ V : Pa Γ, x : Ar E M : C (op : Pa Ar E) Γ E op V (λx M) :C Γ E M : FA Γ H : A E E C Γ E handle M with H : C

λ eff -calculus Type-and-effect system (cntd.) Handler type judgements Γ H : R: Γ, p : Pa, k : U E (Ar C) E M : C... Γ, x : A E N : C Γ op pk M... return x N : A {op:pa Ar,...} E C Note the placement of E s. Type soundness If {} M : FA then M returnv,for V : A.

Why? handler-oriented programming

User-defined effects In Haskell m = do fruit choosefruit form chooseform return $ form + fruit Individually: bothfruit :: [String ] bothfruit =["apple", "orange"] randomform :: IO String randomform = do x getstdrandom random if x then return "raw " else return "cooked "

User-defined effects In Haskell m = do fruit choosefruit form chooseform return $ form + fruit Combined: result :: IO [String ] result = runlistt m choosefruit = ListT $ return bothfruit chooseform = lift $ randomform

Handler-oriented programming Horizontal composition handle (do fruit choosefruit form chooseform return $ form + fruit) (ChooseFruit (λp k do xs k "apple" ys k "orange" return (xs + ys)) ChooseForm (λp k do {v randomform; kv}) Empty, λx return [x ])

Handler-oriented programming Vertical composition handlelistprobv :: IO [ String ] handlelistprobv = handle (handle do fruit choosefruit form chooseform return $ form + fruit) (ChooseFruit (λp k do xs k "apple" ys k "orange" return (xs + ys)) ChooseForm Empty, λx return [x ])) (ChooseForm (λp k do {v randomform; kv}) Empty, return)

Handler-oriented programming Evaluation Is it better than monads? We don t know! Bauer s thesis [private communication] My experience with eff convinces me that we have effects + handlers : delimited continuations = while : goto Our contribution Facilitate investigation: libraries in Haskell, SML, and Racket.

Implementation: free monads Concretely For E = {raise : Exception Empty, lookup : Loc Integer }: data Comp a = Return a Raise Exception Lookup (Loc, Integer Comp a) Consequently: raise e = Raise e lookup m = Lookup (, m) handle (Return a) raisec lookupc returnc = returnc a handle (Raise e) raisec lookupc returnc = raisec e handle (Lookup (, m)) raisec lookupc returnc = lookupc m

Implementation: free monads (cntd.) Typed implementation: Option 1 Use dynamic types and casts: data Comp a = Return a App (Op, Dyn, Dyn Comp a)

Implementation: free monads (cntd.) Option 2 Use GADTs and proxy types: data Comp e a :: where Ret :: a Comp e a App :: Witness op e op Param op (Arity op Comp e a) Comp e a More expressive types (effect polymorphism) = code reuse. Technicalities suggest row polymorphisms as more suitable. Get it from: https://github.com/slindley/effect-handlers

Implementation: delimited control Primitive control operators shift0, reset0: reset0 (E[shift0 (λk M)]) M [(λx reset0 (E[x ])) / k ] Compare with the derived: handle H[op V (λx M)] with... op pk N... N [V / p, (λx handle H[M ] with H) / k ]

Implementation: delimited control (cntd.) The handle construct handle M with H push current effect operation bindings from H onto a stack. reset0 (M) Effect operation op V (λx M) shift0 captures the hoisting context, concatenating it with M use the effect binding from top of the stack to execute op and return is straightforward.

Again? comparison: Filinski s monadic reflection

Conclusion Adequacy Non-free effects What? execution model: SOS, sound effect system Why? handler-oriented programming: expressive implementations Evaluation Dynamic effect generation Performance Again? comparison: Filinski s monadic reflection delimited control Try it, and join the discussion!

Images http://www.agriaffaires.co.uk/img_583/ telescopic-handler/telescopic-handler.jpg http://ginavivinetto.files.wordpress.com/2008/09/ chelsea-handler.jpg