Topic 6: Partial Application, Function Composition and Type Classes

Similar documents
Topic 6: Partial Application, Function Composition and Type Classes

Topic 5: Higher Order Functions

Topic 5: Higher Order Functions

CS 360: Programming Languages Lecture 12: More Haskell

CSC324 Principles of Programming Languages

Programming Paradigms

CSC324 Principles of Programming Languages

Topic 9: Type Checking

Topic 9: Type Checking

Standard prelude. Appendix A. A.1 Classes

Topic 4: Tuples and Lists

CIS 194: Homework 4. Due Wednesday, February 18, What is a Number?

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

CS 320: Concepts of Programming Languages

Topic 7: Algebraic Data Types

Haskell An Introduction

A tour of the Haskell Prelude

Lecture 4: Higher Order Functions

Type-indexed functions in Generic Haskell

Box-and-arrow Diagrams

INTRODUCTION TO HASKELL

Higher Order Functions in Haskell

Haskell Overview II (2A) Young Won Lim 8/9/16

Haskell Types, Classes, and Functions, Currying, and Polymorphism

Introduction to Functional Programming in Haskell 1 / 56

EDAF40. 2nd June :00-19:00. WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read.

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

CSc 372 Comparative Programming Languages

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

Topic 1: Introduction

A general introduction to Functional Programming using Haskell

CSCE 314 Programming Languages

Intro to Haskell Notes: Part 5

Shell CSCE 314 TAMU. Higher Order Functions

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

Haskell-Tutorial. Damir Medak Gerhard Navratil. Institute for Geoinformation Technical University Vienna. February 2003

JVM ByteCode Interpreter

HIGHER-ORDER FUNCTIONS

Lecture 2: List algorithms using recursion and list comprehensions

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Haskell Overview II (2A) Young Won Lim 8/23/16

Haskell Overview II (2A) Young Won Lim 9/26/16

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

Functional Programming Mid-term exam Tuesday 3/10/2017

FUNCTIONAL PROGRAMMING NO.9 TYPE AND CLASS. Tatsuya Hagino

Introduction. chapter Functions

Module 10: Imperative Programming, Modularization, and The Future

Course year Typeclasses and their instances

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

CSCI312 Principles of Programming Languages!

Logic - CM0845 Introduction to Haskell

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

22c:111 Programming Language Concepts. Fall Types I

Introduction to Programming, Aug-Dec 2006

5. Introduction to the Lambda Calculus. Oscar Nierstrasz

Haskell Types COMP360

Topic 8: Lazy Evaluation

Functional Programming and Haskell

Beyond Blocks: Python Session #1

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Type system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited)

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

CS 440: Programming Languages and Translators, Spring 2019 Mon

Overview. Declarative Languages D7012E. Overloading. Overloading Polymorphism Subtyping

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs.

PieNum Language Reference Manual

Programming Paradigms

Introduction to Haskell

6. Pointers, Structs, and Arrays. 1. Juli 2011

Lecture 12: Data Types (and Some Leftover ML)

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

1 Tutorial 1: The simplest case.

Intro. Scheme Basics. scm> 5 5. scm>

Parallel Haskell on MultiCores and Clusters

An introduction introduction to functional functional programming programming using usin Haskell

Functional Programming in Haskell for A level teachers

Talen en Compilers. Jurriaan Hage , period 2. November 13, Department of Information and Computing Sciences Utrecht University

Introduction to Functional Programming

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

SMURF Language Reference Manual Serial MUsic Represented as Functions

CS 11 Haskell track: lecture 1

Functional Programming in Haskell Part 2 : Abstract dataypes and infinite structures

CSc 520. Principles of Programming Languages 11: Haskell Basics

Exercises on ML. Programming Languages. Chanseok Oh

Functional Programming TDA 452, DIT 142

Assignment 1 (Lexical Analyzer)

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

CIS133J. Working with Numbers in Java

Programming with Math and Logic

User-Defined Algebraic Data Types

Title: Recursion and Higher Order Functions

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

The second statement selects character number 1 from and assigns it to.

An Introduction to Python

CIT 590 Homework 6 Fractions

CSC 372 Haskell Mid-term Exam Feburary 28, 2014

Lists. Michael P. Fourman. February 2, 2010

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Transcription:

Topic 6: Partial Application, Function Composition and Type Classes Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 11.11, 11.12 12.30, 12.31, 12.32, 12.33, 12.34, 12.35 13.1, 13.2, 13.3, 13.4, 13.7, 13.8, 13.9, 13.11 If you have time: 12.37, 12.38, 12.39, 12.40, 12.41, 12.42 Readings: Chapter 11.3, and 11.4 Chapter 12.5 Chapter 13.1, 13.2, 13.3 and 13.4 1 2 Functional Forms The parameters to a function can be viewed in two different ways As a single combined unit All values are passed as one tuple How we typically think about parameter passing in Java, C++, Python, Pascal, C#, As a sequence of values that are passed one at a time As each value is passed, a new function is formed that requires one fewer parameters than its predecessor How parameters are passed in Haskell But it s not a detail that we need to concentrate on except when we want to make use of it Curried and Uncurried Forms Uncurried form Parameters are bundled into a tuple and passed as a group Can be used in Haskell Typically only when there is a specific need to do Curried form Parameters are passed to a function sequentially Standard form in Haskell Functions can be transformed from one form to the other 3 4

Curried and Uncurried Forms A function in curried form multiply :: Int > Int > Int multiply x y = x * y A function in uncurried form multiplyuc :: (Int, Int) > Int multiplyuc (x, y) = x * y Curried and Uncurried Forms Why use curried form? Permits partial application Standard way to define functions in Haskell A function of n+1 arguments is an incremental extension of the form for a function with n arguments Why use uncurried form? Syntactically similar to familiar languages Helpful in some situations Mapping / filtering a zipped list 5 6 Curried and Uncurried Forms A curried function can be transformed into an uncurried function Call the uncurry function Takes one parameter, which is a curried function Returns one result, which is a function that performs the same task in uncurried form An uncurried function can be transformed into a curried function Call the curry function Takes one parameter, which is an uncurried function Returns one result, which is a function that performs the same task in curried form Uncurrying Examples Rewrite the following function in uncurried form fma :: Int > Int > Int > Int fma a b c = a * b + c Compute the dot product of [1, 3, 5] and [2, 4, 6] in a single expression Use map, (+), (*), uncurry, zip and foldr1 7 8

Partial Application Consider the function plus :: Int > Int > Int plus x y = x + y Partial Application What happens when we pass plus parameters? What s the type of plus 3 2? What if we only pass plus one parameter? What s the type of plus 1? What s the type of plus? 9 10 Partial Application Partial application allows us to create new functions Set one or more parameters to a specific value, leaving a function that still requires at least one parameter Use the resulting function in any situation where a function is needed Pass it to map, filter, foldl / foldr, zipwith, Example: Write a function that adds 5 to every element in a list of Ints Use map Partial Application Generalize the function that adds a constant value to every element in a list The amount to add will be passed as a second parameter 11 12

Operator Sections Writing a function to add two numbers together seems wasteful The + operator already does this! An operator section is a partial application of an operator Eliminates the need to write functions that duplicate existing operators What s the type of (+) (3 + 3) (3 +) (+ 3) Operator Sections Use map and an operator section to add 5 to every element in a list Use map and an operator section to divide every element in a list by 5 Use map and an operator section compute 5 divided by every element in a list 13 14 Operator Sections Forming a right section of ( ) is problematic ( 3) is the integer minus 3, not a right section of the subtraction operator Solutions to this problem? Use subtract in the prelude function Takes arguments in opposite order you would intuitively expect subtract 4 2 is 2, not 2 subtract 3 is equivalent to right operator section of 3 and ( ) Or use (flip ( ) 3) Example: Subtract 3 from every element in a list Operator Sections Example Write a function that performs a Caesar Cipher Apply a constant offset to every character in a string The offset amount will be a parameter to the function If adding the offset results in a character beyond 127, wrap around to the beginning of the ASCII table Don t use any helper functions 15 16

Partial Application in Other Languages Currying and partial application are now supported in Java Added in Java 8 (March 2014) Syntax isn t as clean as Haskell Default is uncurried import java.util.function.*; class Curried { public static void main(string args[]) { Function<Integer, Function<Integer, Integer>> curriedadd = a > b > a + b; // Form a new function with partial application Function<Integer, Integer> add5 = curriedadd.apply(5); Partial Application in Other Languages Currying and partial application are supported in Python Syntax isn t as clean as Haskell Partial application can be applied to any function // Use curriedadd to compute the sum of 5 and 3 System.out.println(curriedAdd.apply(5).apply(3)); // Use add5 to compute te sum of 5 and 3 System.out.println(add5.apply(3)); } } 17 18 Function Composition Consider our solution to the Caesar Cipher problem Both the Haskell and Python solutions compute the correct result But both have a potential concern, particularly for (very) long strings Function Composition Two (or more) functions can be combined (composed) into a single function What if want to apply h to a parameter x, And then pass the result of that function application as a parameter to g, And then pass the result of that function application as a parameter to f? Until now: Another option: 19 20

Function Composition Example: Write a function that uses tail and reverse to remove the first and last elements from a list Return the empty list if the length of the list is 2 or less Function Composition Example: Consider a module for working with pictures Assume that we already have a function, rotate90cw, that performs a 90 degree clockwise rotation of an image How do we write a function, rotate90ccw, that performs a 90 degree counterclockwise rotation of an image? 21 22 Function Composition The function passed to a higher order function can be A named helper function written by the programmer A named function from a Haskell module A lambda function A partial application of function An operator or operator section A composition of any of the above Function Composition Improve the function that performs a Caesar Cipher Access each element in the list only once Do not create lists of intermediate results Write several different expressions that add 2 to every element in a list of integers 23 24

Function Composition in Other Languages Java Use the compose method Function Composition in Other Langauges There s no standard composition function in Python or C++ But it s possible to write your own Function<Integer, Function<Integer, Integer>> cadd = a > b > a + b; Function<Integer, Function<Integer, Integer>> cflipmod = a > b > b % a; Function<Character, Character> encode = ((Function<Integer, Character>)(Compose::chr)).compose(cFlipMod.apply(128)).compose(cAdd.apply(1)).compose(Compose::ord); Function<Character, Character> decode = ((Function<Integer, Character>)(Compose::chr)).compose(cFlipMod.apply(128)).compose(cAdd.apply( 1)).compose(Compose::ord); 25 26 Polymorphic Functions Revisited We have written polymorphic functions previously Function s type signature includes type variables Function can be applied to values of any type What if we want to write a function that works for some types but not others? Polymorphic Functions Revisited Consider the following function allequal :: a > a > a > Bool allequal x y z = (x == y) && (y == z) It doesn t work correctly Haskell reports an compile time error 27 28

Type Classes Type classes allow restrictions to be placed on type variables Function can be applied to many types, but not all types Restrictions are specified as part of the function s signature Type Classes Consider a polymorphic function that identifies the middle of 3 values What operation(s) must be available? How do we implement the function? A correct version of allequal: 29 30 Type Classes Type Classes Haskell provides numerous built in type classes Equality: Eq Operations: ==, /= Ordering: Ord Operations: <, <=, >=, max, min, compare Enumeration: Enum Operations related to.. Convert to String: Show Operations: show :: a > String, and others Numeric: Num Operations such as addition, subtraction, multiplication, negation, absolute value, Type classes are a hierarchy Ord Enum Integral Eq Real Num RealFrac Show Fractional RealFloat Floating 31 32

Type Classes We can create our own type classes Allow us to impose our own restrictions on the types that can be passed to a polymorphic function Example: What if we wanted to restrict a function to types that can return their length (number of elements)? Type Classes We can form a hierarchy among or own type classes What if we want introduce another type classes that can be empty? Such a type class could be a specialization of the HasLength type class 33 34 Type Classes Example: Create a polymorphic function that returns the status of a data structure that is an instance of CanBeEmpty If the data structure is empty return "Empty" If the data structure contains elements, return "Contains <n> elements" Type Classes in Other Langauges In Java: Classes are types A method restricts the types to which it can be applied based on the static type of its parameters This is much more restrictive than Haskell type classes because it requires a complete subtype relationship between the static type of the method and the dynamic type of the object being passed This doesn t allow one to require multiple type classes A method can require that it s parameter implements a particular interface With generics, one can require that a parameter implement multiple interfaces 35 public <T extends Appendable & Comparable> void doit(t x) { // Do something dependent on both appendable and comparable } 36

Type Classes in Other Languages In Python Type classes don t exist But some functions can still only execute successfully on some types Parameters of any type can be passed to any function call The function body uses whatever methods / operators are needed to perform its work If they aren t defined for the provided types then the program crashes Summary Curried functions take their parameters individually Uncurried functions take their parameters as a tuple Partial application is possible with curried functions A new function is created by fixing a subset of the parameters to an existing function Operator section: Partial application of an operator 37 38 Summary Function composition allows a new function to be created by combining (composing) several functions Type classes allow us to place constraints on the types used by polymorphic functions 39