Functional Programming

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Advertisements

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
Introduction to Recursion and Recursive Algorithms
1 Scheme and Functional Programming Aaron Bloomfield CS 415 Fall 2005.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
Adapted from Scott, Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
Concurrency The need for speed. Why concurrency? Moore’s law: 1. The number of components on a chip doubles about every 18 months 2. The speed of computation.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Recursion. Recursion is a powerful technique for thinking about a process It can be used to simulate a loop, or for many other kinds of applications In.
Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Fall 2011.
16-Jun-15 Recognizers. 2 Parsers and recognizers Given a grammar (say, in BNF) and a string, A recognizer will tell whether the string belongs to the.
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
Hashing. Searching Consider the problem of searching an array for a given value –If the array is not sorted, the search requires O(n) time If the value.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
28-Jun-15 Recognizers. 2 Parsers and recognizers Given a grammar (say, in BNF) and a string, A recognizer will tell whether the string belongs to the.
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Arrays. 2 The array data structure An array is an indexed sequence of components Typically, the array occupies sequential storage locations The length.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
CS TShirts! Congratulations to Emily Kasbohm, whose T-Shirt design won! We will set up a Teespring campaign, and a link to the class if you.
Software design and development Marcus Hunt. Application and limits of procedural programming Procedural programming is a powerful language, typically.
Interlude: Functional Programming CSE 331 Section 2 James Daly.
Clojure 3 Recursion, Higher-order-functions 27-Aug-15.
Language Evaluation Criteria
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Lists in Python.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Storage Management. The stack and the heap Dynamic storage allocation refers to allocating space for variables at run time Most modern languages support.
Apr 17, 2013 Persistent Data Structures. Definitions An immutable data structure is one that, once created, cannot be modified Immutable data structures.
Feb 7, 2015 Thinking in Clojure. Jumping in We’ll quickly go through Clojure’s data types, some basic functions, and basic syntax Then we’ll get to the.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
Copyright © Genetic Computer School 2008 Computer Systems Architecture SA 7- 0 Lesson 7 Memory Management.
CMSC 330: Organization of Programming Languages Maps and Folds Anonymous Functions.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
27-Jan-16 Analysis of Algorithms. 2 Time and space To analyze an algorithm means: developing a formula for predicting how fast an algorithm is, based.
Question of the Day  What three letter word completes the first word and starts the second one: DON???CAR.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2014 Curt Hill Algorithms From the Mathematical Perspective.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Copyright © 2009 Elsevier Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
CSE 341 : Programming Languages Lecture 9 Lexical Scope, Closures Zach Tatlock Spring 2014.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
CSE-321 Programming Languages Introduction to Functional Programming POSTECH March 8, 2006 박성우.
Functional Processing of Collections (Advanced) 6.0.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Assignment 5 is posted. Exercise 8 is very similar to what you will be doing with assignment 5. Exam.
Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Thursday, April 9,
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Clojure Macros. Homoiconicity All versions of Lisp, including Clojure, are homoiconic This means that there is no difference between the form of the data.
Functional Programming
Functional Processing of Collections (Advanced)
Chap. 6 :: Control Flow Michael L. Scott.
Important Concepts from Clojure
Important Concepts from Clojure
COS 260 DAY 10 Tony Gauvin.
Chap. 6 :: Control Flow Michael L. Scott.
Recursion, Higher-order-functions
Announcements Quiz 5 HW6 due October 23
Important Concepts from Clojure
Lisp.
Presentation transcript:

Functional Programming And Why It Matters

In the beginning… There were the forces of light… There were the forces of darkness… Actually, there were two very early higher level languages, Fortran and Lisp Fortran was an imperative language, and became mainstream Lisp was a functional language, with fewer followers Both languages had many descendants Fortran: C, Algol, Pascal, Python, etc., plus modern versions of Fortran Lisp: Erlang, Haskell, OCaml, etc., plus modern versions of Lisp (such as Clojure)

Why did Fortran pull ahead? Fortran was slightly earlier in time A great deal of work was put into optimizing Fortran, so that it could compete with assembly language Fortran was (and is) better for heavy number crunching, which made it more suitable for military uses

The Lisp influence “All languages converge to Lisp.” -- Anonymous Modern languages all contain many features that originated in Lisp What did Lisp have that Fortran didn’t? Recursion Automatic garbage collection Data structures other than arrays What does Lisp have that Java 7 still doesn’t? Functions (not the same as methods!) Ability to treat functions as values Immutable (persistent) data structures Macros C has “macros”, but they are difficult and badly integrated into the language Homoiconicity

Functions as values All modern languages have recursion, automatic garbage collection (except C++), and a variety of data structures Many languages now have the ability to treat a function as an ordinary value (like an integer or a string) There is a way to write a “literal” (anonymous) function Functions can be stored in variables and in collections Functions can be passed as parameters to functions Functions can be returned as the result of a function There are operators to combine functions into new functions

Functions in FP languages Given a set of input values, a function produces an output value Given the same input values, a function always produces the same output value Functions can use only the information provided by their parameters This excludes “functions” that return the date, the time, or a random number Functions have no side effects Functions don’t do input or output Functions don’t change the values of any variables or data Functions only return a value Consequently, functions are easier to reason about To understand a function, you need examine only the function itself A function can use other functions, and of course you need to know what those functions are supposed to compute (but nothing about how they do it) In addition, functions can be called in any order, including in parallel

Immutable and persistent data structures An immutable data structure is one that, once created, cannot be modified Immutable data structures can (usually) be copied, with modifications, to create a new version The modified version takes up as much memory as the original version If all data is immutable, we may need infeasible amounts of memory A persistent data structure is one that, when modified, retains both the old and the new values Persistent data structures are effectively immutable, in that prior references to it do not see any change Modifying a persistent data structure may copy part of the original, but the new version shares memory with the original We generally talk about functional programming as having immutable data, but really it’s persistent

Lists Lists are the original persistent data structures, and are very heavily used in functional programming w [w, x, y, z] x z y [x, y, z] [y, z] The tail of [x, y, z] is [y, z]. Adding an element w to [x, y, z] doesn’t change [x, y, z] itself. 8

Immutable values Fundamental to functional programming is that all data is immutable or persistent You can only compute new data from it Structure sharing makes this feasible Consequences: Lists, not arrays, are the fundamental data structure Arrays are designed for random access; lists are designed for working from one end Complex data structures can be built more easily from lists than from arrays Recursion replaces loops as a fundamental “control structure” You never need to protect data with mutexes (locks)

“No silver bullet” There are language zealots that will try to convince you that some particular language (usually Lisp) will solve all the worlds problems. If Lisp is so great, why isn’t everybody using it? In a sense, both Lisp and Prolog are “perfect,” or nearly so Both are direct computer implementations of beautiful mathematical structures Both are extremely powerful in certain domains “In theory, there is no difference between theory and practice. But in practice, there is.” -- Jan L. A. van de Snepscheut Functional programming will not solve all the world’s problems, but… It solves an awful lot of problems when doing concurrent programming It provides some really nice tools even when you aren’t doing concurrent programming

Working with lists Arrays: Loop over the array, doing something with each element in turn Lists: Do something with the head, and recur with the tail Head: The first element in the list Tail: The list that remains when you step past the head. Occasionally you may need to work at the “wrong end” of a list General solution: Reverse the list, work at the head, and reverse the result

Basic list operations There aren’t very many Get the head of the list (hd in Erlang) Get the tail of the list (tl in Erlang) Add a new element E to the list L ([E|L] in Erlang) Test if a list is empty (L==[] in Erlang)

Recursion on lists Basic strategy: Return some value if the list is empty Do something with the head Recur with the tail Finding the length of a list (Do It Yourself version): myLength([]) -> 0; myLength([_|T]) -> 1 + myLength(T). Again, but with tail recursion: myLengthTR(List) -> myLengthHelper(0, List). myLengthHelper(Acc, []) -> Acc; myLengthHelper(Acc, [_|T]) -> myLengthHelper(Acc + 1, T).

Standard higher-order functions A higher-order function is a function that (1) takes a function as a parameter, or (2) returns a function as its value, or both map(Fun, List) Applies Fun to each element of List, returning a list of the results. The result may contain values of a type different that those in List . filter(Pred, List) Returns a list of the elements of List that satisfy the predicate Pred. The result will be a sublist of List . The following standard function comes in a variety of flavors—whether it works left to right or right to left, and whether it needs an explicit accumulator foldl(Fun, Acc, List) Calls Fun on successive pairs of elements of List , starting with Acc The type returned is the type of Acc

More higher-order functions all(Pred, List) any(Pred, List) takewhile(Pred, List) dropwhile(Pred, List) flatten(DeepList) flatmap(Fun, List) foreach(Fun, List) partition(Pred, List) zip(List1, List2) unzip(List)

takewhile in Java Suppose you have a list of numbers, and you want a new list consisting of only the positive numbers at the beginning of the given list List newList<Integer> = new LinkedList<>(); for (int e : oldList) { if (e <= 0) break; newList.append(e); } That’s not as easy as takewhile(fun(X) -> X > 0 end, List) but you can work through it without too much difficulty Suppose you also want to get only the even numbers at the beginning, or only the prime numbers, or only ones less than 100 You cannot reuse the above Java code; you have to do it all over again!

Loop elimination Good code is clear and easy to understand takewhile(fun(X) -> X > 0 end, List) is clear and easy to understand (once you know the syntax) Loops always need to be worked through in order to understand them (well, almost always) for (int i; i < array.length; i++) array[i] = 0; is pretty clear Functional programming languages typically provide quite a few very useful higher-order functions In a lot of cases, these functions can replace loops FP languages may also provide list comprehensions, which again are clearer than loops, and can often replace them When all else fails, loops can be replaced by recursion, which is (arguably) no harder to understand than loops

Functions that return functions Erlang has a built-in version of quicksort, but you could write your own: quicksort([]) -> []; quicksort([H | T]) -> quicksort( [ X || X <- T, X < H ]) ++ [H] ++ quicksort([ X || X <- T, X >= H ]). But what if you wanted to sort something other than numbers, say, student records? The key point to notice is that X < H (and X >= H, which is really just not(X < H)) is just a binary predicate You could rewrite this function to pass in some binary predicate You could also write a function that takes in just a binary predicate, and returns a sort function

Summary In a functional language, especially a “pure” one, you lose: Global variables The ability to change the values of variables The ability to write loops You gain: The ability to treat functions just like any other values A useful set of higher-order functions More ways to avoid code duplication (DRY) Far better ways to deal with concurrency

The End

I’m thinking of something. Animal Vegetable Mineral 16