Higher-Order Functions 15-150: Principles of Functional Programming – Lecture 13

Total Page:16

File Type:pdf, Size:1020Kb

Higher-Order Functions 15-150: Principles of Functional Programming – Lecture 13 Higher-order Functions 15-150: Principles of Functional Programming { Lecture 13 Giselle Reis By now you might feel like you have a pretty good idea of what is going on in functional program- ming, but in reality we have used only a fragment of the language. In this lecture we see what more we can do and what gives the name functional to this paradigm. Let's take a step back and look at ML's typing system: we have basic types (such as int, string, etc.), tuples of types (t*t' ) and functions of a type to a type (t ->t' ). In a grammar style (where α is a basic type): τ ::= α j τ ∗ τ j τ ! τ What types allowed by this grammar have we not used so far? Well, we could, for instance, have a function below a tuple. Or even a function within a function, couldn't we? The following are completely valid types: int*(int -> int) int ->(int -> int) (int -> int) -> int The first one is a pair in which the first element is an integer and the second one is a function from integers to integers. The second one is a function from integers to functions (which have type int -> int). The third type is a function from functions to integers. The two last types are examples of higher-order functions1, i.e., a function which: • receives a function as a parameter; or • returns a function. Functions can be used like any other value. They are first-class citizens. Maybe this seems strange at first, but I am sure you have used higher-order functions before without noticing it. For example, callback functions are usually passed as a parameter to other functions. In math, derivatives are nothing but a function which operates on functions (also integrals). In fact, let's look at the case of derivatives. There are two ways to compute derivatives of a function f at a point x. One is via the definition: f(x + δ) − f(x) f 0(x) = lim δ!0 δ But soon after learning that, you also learn some rules of computation which avoid having to compute this limit all the time (e.g. if f(x) = xn then f 0(x) = nxn−1). To use the rules, though, we need to know what the function looks like, whereas the definition works regardless of the structure of f. In other words, the definition treats f as a black-box. This is how we shall treat functions inside higher-order functions in ML. Now let's look at some concrete examples2. Take the function that increments a number by a δ: inc : N × N ! N inc(δ; x) = x + δ It's a pretty simple function. 1Analogously, the first type is that of higher-order tuple. 2We stay in math for now. We will see the SML syntax for all this soon, but for now concentrate on the concepts. 1 Now let's implement a function that, given δ, generates the inc function for that δ. So that will be a function that returns a function, and its type is: mkInc : N ! (N ! N) There is not much secret to this definition, really. There are two ways in which this can be done. One way is to define the returning function with a name and return this name: mkInc(δ) = f where f(x) = x + δ With all you know about SML so far, you could already implement such function. The other way is to keep the function nameless, i.e., use an anonymous function. Does that ring a bell? Anonymous functions are declared using λ notation: mkInc(δ) = λx.x + δ Remark 1. The use of λ for anonymous function follows the notation used in the λ-calculus, a very famous model of computation on which functional programming is based. In this model there are only three constructs (one being anonymous functions) and it can be used to simulate Turing machines (meaning it is Turing-complete). λ-calculus was proposed by Alonzo Church in 1936. Here are some examples of functions using λ notation and their named version (using f): Identity λx.x f(x) = x g ◦ h λx.g(h(x)) f(x) = g(h(x)) First of a pair (uncurried) λ(x; y):x f(x; y) = x First of a pair (curried) λx.λy:x f x y = x You are free to use any notation you want. Once you get used to the λ-notation, it might become less clumsy than giving names to all the functions. Let's use our mkInc function to build a function that incremets numbers by 1: incOne = mkInc 1 Since incOne has type N ! N, we can apply it to a number: incOne 15 = 16 In fact, we can completely bypass the creation of incOne: (mkInc 1) 15 = 16 Remember the type of mkInc : N ! (N ! N). It takes one integer and returns a function, that is what is happenning in mkInc 1. This function has type N ! N, so we go ahead and apply it to 15 to get the final value: the integer 16. Interestingly, we could have done the same with inc, but we would have to give it the pair (1; 15) as argument. These two functions do the same thing, but they have different types: inc : N × N ! N mkInc : N ! (N ! N) The second type is said to be curried3. It turns out we can always transform a function application to a tuple (i.e., uncurried) into a curried type. This is called currying. The opposite is also possible, we can uncurry a function. Notice though that in this case a partial application of the function is no longer possible. We could create incOne with mkInc, but if we are going to use inc, all arguments must be there. 3After Haskell Curry, the guy who also gives the name to the language Haskell. 2 Currying and uncurrying change the type of the function, so this does not mean we can use mkInc (1; 15) for example. This does not typecheck. The function arrow associates to the right, and function application associates to the left, so we can drop the parentheses and write N ! N ! N for the type and mkInc 1 15 for the application. To think: Why does it make sense for function application to be left-associative and its type to be right-associative? Let us look at a more interesting example. We will use one of our favorite data-structures for that: trees. Suppose we have the following tree where all leaves have implicit empty children (i.e., leaves are node(empty; ; empty)). It stores countries and its area in ×1000km2. (\India",3287) (\Egypt",1000) (\Nepal",147) (\Brazil",8515) (\Fiji",18) (\Jordan",92) (\Qatar",11) Suppose we want to ommit the number of the area itself, and keep only the name of the country. You can certainly define a function that does that: name (empty) = empty name (node(tl; (n; a); tr)) = node(name(tl); n; name(tr)) Now you need to change the areas to ×106km2. That is also a simple function: areaNorm (empty) = empty areaNorm (node(tl; (n; a); tr)) = node(areaNorm(tl); (n; a=1000); areaNorm(tr)) These two functions follow the same pattern. Can we use our abstraction power and what we learned so far about higher-order functions to avoid having to type the same thing again and again? The two functions traverse the tree the same way, the only thing that changes is the operation done on the data in the nodes. We can thus parametrize the function by this operation (which will be a function itself). map f empty = empty map f (node(tl; x; tr)) = node(map f tl; f(x); map f tr) This operation is called map. Observe that we do not even require that the data within the nodes is a pair. It could be anything. Using map, we can redefine name and areaNorm in one line each: noName = map (λ(n; a):a) areaNorm = map (λ(n; a):(n; a=1000)) We might also need functions that compute some value depending on the content of the tree, instead of reconstructing it with other data. For example, we might want to find the areas of the biggest and smallest countries. The functions that compute these values are the following: biggest empty = 0 biggest node(tl; (n; a); tr) = max(biggest tl; a; biggest tr) smallest empty = 20000 smallest node(tl; (n; a); tr) = min(smallest tl; a; smallest tr) We can again use higher-order functions to simplify these definitions, but we need something more. Notice that not only the function (max=min) used is different, but also the value in the base case. These two elements are the parameters for the reduce function: 3 reduce f e empty = e reduce f e node(tl; x; tr) = f(reduce f e tl; x; reduce f e tr) The functions biggest and smallest become: biggest = reduce (λ(x; (n; a); y):max(x; a; y)) 0 smallest = reduce (λ(x; (n; a); y):min(x; a; y)) 20000 Notice how max and min are used inside a λ function which takes the needed element from the tuple. The functions map and reduce can also be defined for lists. The only difference is that reduce is called fold, and there are two different ways to reduce. Map is straightforward: map f [] = [] map f (x :: l) = f(x) :: (map f l) Folding can be done using fold-right (foldr) or fold-left (foldl).
Recommended publications
  • Lecture 4. Higher-Order Functions Functional Programming
    Lecture 4. Higher-order functions Functional Programming [Faculty of Science Information and Computing Sciences] 0 I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state [Faculty of Science Information and Computing Sciences] 1 I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto [Faculty of Science Information and Computing Sciences] 1 I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell [Faculty of Science Information and Computing Sciences] 1 Goal
    [Show full text]
  • Typescript Language Specification
    TypeScript Language Specification Version 1.8 January, 2016 Microsoft is making this Specification available under the Open Web Foundation Final Specification Agreement Version 1.0 ("OWF 1.0") as of October 1, 2012. The OWF 1.0 is available at http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0. TypeScript is a trademark of Microsoft Corporation. Table of Contents 1 Introduction ................................................................................................................................................................................... 1 1.1 Ambient Declarations ..................................................................................................................................................... 3 1.2 Function Types .................................................................................................................................................................. 3 1.3 Object Types ...................................................................................................................................................................... 4 1.4 Structural Subtyping ....................................................................................................................................................... 6 1.5 Contextual Typing ............................................................................................................................................................ 7 1.6 Classes .................................................................................................................................................................................
    [Show full text]
  • Scala Tutorial
    Scala Tutorial SCALA TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Scala Tutorial Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003. Scala smoothly integrates features of object-oriented and functional languages. This tutorial gives a great understanding on Scala. Audience This tutorial has been prepared for the beginners to help them understand programming Language Scala in simple and easy steps. After completing this tutorial, you will find yourself at a moderate level of expertise in using Scala from where you can take yourself to next levels. Prerequisites Scala Programming is based on Java, so if you are aware of Java syntax, then it's pretty easy to learn Scala. Further if you do not have expertise in Java but you know any other programming language like C, C++ or Python, then it will also help in grasping Scala concepts very quickly. Copyright & Disclaimer Notice All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] TUTORIALS POINT Simply Easy Learning Table of Content Scala Tutorial ..........................................................................
    [Show full text]
  • Smalltalk Smalltalk
    3/8/2008 CSE 3302 Programming Languages Smalltalk Everyygthing is obj ect. Obj ects communicate by messages. Chengkai Li Spring 2008 Lecture 14 – Smalltalk, Spring Lecture 14 – Smalltalk, Spring CSE3302 Programming Languages, UT-Arlington 1 CSE3302 Programming Languages, UT-Arlington 2 2008 ©Chengkai Li, 2008 2008 ©Chengkai Li, 2008 Object Hierarchy Object UndefinedObject Boolean Magnitude Collection No Data Type. True False Set … There is only Class. Char Number … Fraction Integer Float Lecture 14 – Smalltalk, Spring Lecture 14 – Smalltalk, Spring CSE3302 Programming Languages, UT-Arlington 3 CSE3302 Programming Languages, UT-Arlington 4 2008 ©Chengkai Li, 2008 2008 ©Chengkai Li, 2008 Syntax • Smalltalk is really “small” – Only 6 keywords (pseudo variables) – Class, object, variable, method names are self explanatory Sma llta lk Syn tax is Simp le. – Only syntax for calling method (messages) and defining method. • No syntax for control structure • No syntax for creating class Lecture 14 – Smalltalk, Spring Lecture 14 – Smalltalk, Spring CSE3302 Programming Languages, UT-Arlington 5 CSE3302 Programming Languages, UT-Arlington 6 2008 ©Chengkai Li, 2008 2008 ©Chengkai Li, 2008 1 3/8/2008 Expressions Literals • Literals • Number: 3 3.5 • Character: $a • Pseudo Variables • String: ‘ ’ (‘Hel’,’lo!’ and ‘Hello!’ are two objects) • Symbol: # (#foo and #foo are the same object) • Variables • Compile-time (literal) array: #(1 $a 1+2) • Assignments • Run-time (dynamic) array: {1. $a. 1+2} • Comment: “This is a comment.” • Blocks • Messages Lecture 14 – Smalltalk, Spring Lecture 14 – Smalltalk, Spring CSE3302 Programming Languages, UT-Arlington 7 CSE3302 Programming Languages, UT-Arlington 8 2008 ©Chengkai Li, 2008 2008 ©Chengkai Li, 2008 Pseudo Variables Variables • Instance variables.
    [Show full text]
  • Python Functions
    PPYYTTHHOONN FFUUNNCCTTIIOONNSS http://www.tutorialspoint.com/python/python_functions.htm Copyright © tutorialspoint.com A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print, etc. but you can also create your own functions. These functions are called user-defined functions. Defining a Function You can define functions to provide the required functionality. Here are simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses ( ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon : and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. Syntax def functionname( parameters ): "function_docstring" function_suite return [expression] By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. Example The following function takes a string as input parameter and prints it on standard screen. def printme( str ): "This prints a passed string into this function" print str return Calling a Function Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
    [Show full text]
  • Clojure, Given the Pun on Closure, Representing Anything Specific
    dynamic, functional programming for the JVM “It (the logo) was designed by my brother, Tom Hickey. “It I wanted to involve c (c#), l (lisp) and j (java). I don't think we ever really discussed the colors Once I came up with Clojure, given the pun on closure, representing anything specific. I always vaguely the available domains and vast emptiness of the thought of them as earth and sky.” - Rich Hickey googlespace, it was an easy decision..” - Rich Hickey Mark Volkmann [email protected] Functional Programming (FP) In the spirit of saying OO is is ... encapsulation, inheritance and polymorphism ... • Pure Functions • produce results that only depend on inputs, not any global state • do not have side effects such as Real applications need some changing global state, file I/O or database updates side effects, but they should be clearly identified and isolated. • First Class Functions • can be held in variables • can be passed to and returned from other functions • Higher Order Functions • functions that do one or both of these: • accept other functions as arguments and execute them zero or more times • return another function 2 ... FP is ... Closures • main use is to pass • special functions that retain access to variables a block of code that were in their scope when the closure was created to a function • Partial Application • ability to create new functions from existing ones that take fewer arguments • Currying • transforming a function of n arguments into a chain of n one argument functions • Continuations ability to save execution state and return to it later think browser • back button 3 ..
    [Show full text]
  • Topic 6: Partial Application, Function Composition and Type Classes
    Recommended Exercises and Readings Topic 6: Partial Application, • From Haskell: The craft of functional programming (3rd Ed.) Function Composition and Type • Exercises: • 11.11, 11.12 Classes • 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 Curried and Uncurried Forms • The parameters to a function can be viewed in two different ways • Uncurried form • As a single combined unit • Parameters are bundled into a tuple and passed as a group • All values are passed as one tuple • Can be used in Haskell • How we typically think about parameter passing in Java, C++, Python, Pascal, C#, … • Typically only when there is a specific need to do • 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 • Curried form than its predecessor • Parameters are passed to a function sequentially • How parameters are passed in Haskell • Standard form in Haskell • But it’s not a detail that we need to concentrate on except when we want to make use of it • Functions can be transformed from one form to the other 3 4 Curried and Uncurried Forms Curried and Uncurried Forms • A function in curried form • Why use curried form? • Permits partial application multiply :: Int ‐> Int ‐> Int • Standard way to define functions in Haskell multiply x y = x * y • A function of n+1
    [Show full text]
  • An Overview of the Scala Programming Language
    An Overview of the Scala Programming Language Second Edition Martin Odersky, Philippe Altherr, Vincent Cremet, Iulian Dragos Gilles Dubochet, Burak Emir, Sean McDirmid, Stéphane Micheloud, Nikolay Mihaylov, Michel Schinz, Erik Stenman, Lex Spoon, Matthias Zenger École Polytechnique Fédérale de Lausanne (EPFL) 1015 Lausanne, Switzerland Technical Report LAMP-REPORT-2006-001 Abstract guage for component software needs to be scalable in the sense that the same concepts can describe small as well as Scala fuses object-oriented and functional programming in large parts. Therefore, we concentrate on mechanisms for a statically typed programming language. It is aimed at the abstraction, composition, and decomposition rather than construction of components and component systems. This adding a large set of primitives which might be useful for paper gives an overview of the Scala language for readers components at some level of scale, but not at other lev- who are familar with programming methods and program- els. Second, we postulate that scalable support for compo- ming language design. nents can be provided by a programming language which unies and generalizes object-oriented and functional pro- gramming. For statically typed languages, of which Scala 1 Introduction is an instance, these two paradigms were up to now largely separate. True component systems have been an elusive goal of the To validate our hypotheses, Scala needs to be applied software industry. Ideally, software should be assembled in the design of components and component systems. Only from libraries of pre-written components, just as hardware is serious application by a user community can tell whether the assembled from pre-fabricated chips.
    [Show full text]
  • Scala Is an Object Functional Programming and Scripting Language for General Software Applications Designed to Express Solutions in a Concise Manner
    https://www.guru99.com/ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1) Explain what is Scala? Scala is an object functional programming and scripting language for general software applications designed to express solutions in a concise manner. 2) What is a ‘Scala set’? What are methods through which operation sets are expressed? Scala set is a collection of pairwise elements of the same type. Scala set does not contain any duplicate elements. There are two kinds of sets, mutable and immutable. 3) What is a ‘Scala map’? Scala map is a collection of key or value pairs. Based on its key any value can be retrieved. Values are not unique but keys are unique in the Map. 4) What is the advantage of Scala? • Less error prone functional style • High maintainability and productivity • High scalability • High testability • Provides features of concurrent programming 5) In what ways Scala is better than other programming language? • The arrays uses regular generics, while in other language, generics are bolted on as an afterthought and are completely separate but have overlapping behaviours with arrays. • Scala has immutable “val” as a first class language feature. The “val” of scala is similar to Java final variables. Contents may mutate but top reference is immutable. • Scala lets ‘if blocks’, ‘for-yield loops’, and ‘code’ in braces to return a value. It is more preferable, and eliminates the need for a separate ternary
    [Show full text]
  • Functional Programming Lecture 1: Introduction
    Functional Programming Lecture 13: FP in the Real World Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague [email protected] 1 Mixed paradigm languages Functional programming is great easy parallelism and concurrency referential transparency, encapsulation compact declarative code Imperative programming is great more convenient I/O better performance in certain tasks There is no reason not to combine paradigms 2 3 Source: Wikipedia 4 Scala Quite popular with industry Multi-paradigm language • simple parallelism/concurrency • able to build enterprise solutions Runs on JVM 5 Scala vs. Haskell • Adam Szlachta's slides 6 Is Java 8 a Functional Language? Based on: https://jlordiales.me/2014/11/01/overview-java-8/ Functional language first class functions higher order functions pure functions (referential transparency) recursion closures currying and partial application 7 First class functions Previously, you could pass only classes in Java File[] directories = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); Java 8 has the concept of method reference File[] directories = new File(".").listFiles(File::isDirectory); 8 Lambdas Sometimes we want a single-purpose function File[] csvFiles = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getAbsolutePath().endsWith("csv"); } }); Java 8 has lambda functions for that File[] csvFiles = new File(".")
    [Show full text]
  • Notes on Functional Programming with Haskell
    Notes on Functional Programming with Haskell H. Conrad Cunningham [email protected] Multiparadigm Software Architecture Group Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA Fall Semester 2014 Copyright c 1994, 1995, 1997, 2003, 2007, 2010, 2014 by H. Conrad Cunningham Permission to copy and use this document for educational or research purposes of a non-commercial nature is hereby granted provided that this copyright notice is retained on all copies. All other rights are reserved by the author. H. Conrad Cunningham, D.Sc. Professor and Chair Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA [email protected] PREFACE TO 1995 EDITION I wrote this set of lecture notes for use in the course Functional Programming (CSCI 555) that I teach in the Department of Computer and Information Science at the Uni- versity of Mississippi. The course is open to advanced undergraduates and beginning graduate students. The first version of these notes were written as a part of my preparation for the fall semester 1993 offering of the course. This version reflects some restructuring and revision done for the fall 1994 offering of the course|or after completion of the class. For these classes, I used the following resources: Textbook { Richard Bird and Philip Wadler. Introduction to Functional Program- ming, Prentice Hall International, 1988 [2]. These notes more or less cover the material from chapters 1 through 6 plus selected material from chapters 7 through 9. Software { Gofer interpreter version 2.30 (2.28 in 1993) written by Mark P.
    [Show full text]
  • Currying and Partial Application and Other Tasty Closure Recipes
    CS 251 Fall 20192019 Principles of of Programming Programming Languages Languages λ Ben Wood Currying and Partial Application and other tasty closure recipes https://cs.wellesley.edu/~cs251/f19/ Currying and Partial Application 1 More idioms for closures • Function composition • Currying and partial application • Callbacks (e.g., reactive programming, later) • Functions as data representation (later) Currying and Partial Application 2 Function composition fun compose (f,g) = fn x => f (g x) Closure “remembers” f and g : ('b -> 'c) * ('a -> 'b) -> ('a -> 'c) REPL prints something equivalent ML standard library provides infix operator o fun sqrt_of_abs i = Math.sqrt(Real.fromInt(abs i)) fun sqrt_of_abs i = (Math.sqrt o Real.fromInt o abs) i val sqrt_of_abs = Math.sqrt o Real.fromInt o abs Right to left. Currying and Partial Application 3 Pipelines (left-to-right composition) “Pipelines” of functions are common in functional programming. infix |> fun x |> f = f x fun sqrt_of_abs i = i |> abs |> Real.fromInt |> Math.sqrt (F#, Microsoft's ML flavor, defines this by default) Currying and Partial Application 4 Currying • Every ML function takes exactly one argument • Previously encoded n arguments via one n-tuple • Another way: Take one argument and return a function that takes another argument and… – Called “currying” after logician Haskell Curry Currying and Partial Application 6 Example val sorted3 = fn x => fn y => fn z => z >= y andalso y >= x val t1 = ((sorted3 7) 9) 11 • Calling (sorted3 7) returns a closure with: – Code fn y => fn z
    [Show full text]