Functional Programming Shane Carr CSE 232, September 4, 2015.

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

1 Scheme and Functional Programming Aaron Bloomfield CS 415 Fall 2005.
Adapted from Scott, Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
CSE 3341/655; Part 4 55 A functional program: Collection of functions A function just computes and returns a value No side-effects In fact: No program.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Apply-to-all A functional form that takes a single function as a parameter and yields a list of values obtained.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
CSE 341, Winter Type Systems Terms to learn about types: –Type –Type system –Statically typed language –Dynamically typed language –Type error –Strongly.
Arrays Liang, Chpt 5. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.
The Scheme Programming Language History and Significance Dmitry Nesvizhsky CIS24 Professor Danny Kopec.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Programming Language Theory Leif Grönqvist The national Graduate School of Language Technology (GSLT) MSI.
Introducing Hashing Chapter 21 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Abstract Data Types (ADTs) Data Structures The Java Collections API
Chapter 17 Java SE 8 Lambdas and Streams
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
Lists in Python.
Technical Interviews Shane Carr CSE 232, September 11, 2015.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui SWEN 432 Advanced Database Design and Implementation MongoDB Aggregation.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
CSC 580 – Theory of Programming Languages, Spring, 2009 Week 9: Functional Languages ML and Haskell, Dr. Dale E. Parson.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Comparative Programming Languages Language Comparison: Scheme, Smalltalk, Python, Ruby, Perl, Prolog, ML, C++/STL, Java, Haskell.
TIVDM2Functional Programming Language Concepts 1 Concepts from Functional Programming Languages Peter Gorm Larsen.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Cs1321 December 6, 2001 Review. What is computer science? What's an algorithm? Processes and programs Overview of some programming language concepts Functional.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
List Interface and Linked List Mrs. Furman March 25, 2010.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
Cs3180 (Prasad)L156HOF1 Higher-Order Functions. cs3180 (Prasad)L156HOF2 Equivalent Notations (define (f x y) (… body …)) = (define f (lambda (x y) (…
Python Programing: An Introduction to Computer Science
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
Functional Processing of Collections (Advanced) 6.0.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Building Java Programs Chapter 19 Functional Programming with Java 8 Copyright (c) Pearson All rights reserved.
CS314 – Section 5 Recitation 9
Information and Computer Sciences University of Hawaii, Manoa
CS314 – Section 5 Recitation 10
dr Robert Kowalczyk WMiI UŁ
ML: a quasi-functional language with strong typing
Algorithmic complexity: Speed of algorithms
Functional Programming and Stream API
Containers and Lists CIS 40 – Introduction to Programming in Python
Functional Processing of Collections (Advanced)
PROGRAMMING IN HASKELL
COS 260 DAY 10 Tony Gauvin.
int [] scores = new int [10];
FP Foundations, Scheme In Text: Chapter 14.
Closure Closure binds a first-class function and a lexical environment together This is a complex topic, so we will build up our understanding of it we.
CS 36 – Chapter 11 Functional programming Features Practice
Building Java Programs Chapter 19
Algorithmic complexity: Speed of algorithms
Building Java Programs Chapter 19
int [] scores = new int [10];
Announcements Quiz 5 HW6 due October 23
Algorithmic complexity: Speed of algorithms
Type Systems Terms to learn about types: Related concepts: Type
„Lambda expressions, Optional”
Presentation transcript:

Functional Programming Shane Carr CSE 232, September 4, 2015

Upcoming Events  CodeSprint  Starts next week (September 11)  5 points of course credit  10 points of extra credit available  Teams of 1-3  Smaller teams don’t need to solve as many problems (1 problem per person for full credit)  ICPC Qualifiers  Saturday, October 3 (sign up by September 16)  15 points of course credit

Cut the Sticks: Language Breakdown

Cut the Sticks: Approach Breakdown

Cut the Sticks: Time Taken (minutes)

Functional Programming

What’s wrong with the following code? // “strs” is a string array // We want to get an array // containing the lengths // of the strings in “strs” int[] result = new int[strs.length]; for(int i = 0; i < strs.length; i++) { String str = strs[i]; result[i] = str.length(); }  The code works.  We are telling the computer how to compute the result array.  What if we could tell the computer what we wanted to compute, and let the computer figure out the best way to do it?

Imperative vs. Functional You tell the computer how to perform a task. Imperative Programming You tell the computer what you want, and you let the computer (i.e. the compiler or runtime) figure out for itself the best way to do it. Functional Programming

Java 8: Lambdas and Streams  Lambdas  Like “mini functions”  Streams  Similar to lists, but provide functional programming constructs and perform lazy evaluation // Convert List to Stream // (constant time) Stream myStream = myList.stream(); // Convert Stream to List // (linear time) List myList = myStream.collect( Collectors.toList());

Functional Array Operations Filter, Map, Reduce, and others

Filter Keep elements that pass a boolean test // Java 8 Stream filtered = myStream.filter (s -> s.length() > 5); # Python (full syntax) filtered = filter( lambda s: len(s) > 5, source) # Python (shortcut syntax) filtered = \ (s for s in source if len(s) > 5) // Java 7 List result = new ArrayList (); for (String str : myList) { if (str.length() > 5) { result.add(str); }

Find Return one element satisfying a boolean test // Java 8 Optional result = myStream.filter (s -> s.length() == 5).findAny(); # Python filtered = next( (s for s in source if len(s) == 5), "not found") // Java 7 String result = null; for (String str : myList) { if (str.length() == 5) { result = str; break; } Note: Under the hood, Java 8 and Python both use lazy evaluation, so neither language traverses the entire stream if it finds a matching element early in the stream.

Map Transform elements by a common operation // Java 8 Stream lens = myStream.map(s -> s.length()); # Python lens = \ (len(s) for s in source) // Java 7 List lens = new ArrayList (); for (String str : myList) { lens.add(str.length()); }

Reduce Apply a binary operation to all elements // Java 8 int totalLen = myStream.reduce(0, (t,s) -> t + s.length(), Integer::sum); # Python from functools import reduce totalLen = reduce( lambda t,s: t + len(s), source, 0) // Java 7 int totalLen = 0; for (String str : myList) { totalLen += str.length(); }

Convenience Reducers Min, Max, Sum, Average, Count, etc. // Java 8 OptionalDouble avgLen = myStream.mapToInt (s -> s.length()).average(); # Python 3.4 from statistics import mean totalLen = mean( len(s) for s in source) // Java 7 int totalLen = 0; for (String str : myList) { totalLen += str.length(); } double avgLen = ((double)totalLen) / myList.size();

Collect Aggregate elements (for example, grouping) // Java 8 Map > byLength = myStream.collect( Collectors.groupingBy( String::length)); # Python # caveat: requires a sorted # list before grouping totalLen = groupby( source, key = lambda s: len(s)) // Java 7 Map > byLength = new HashMap<Integer, List >(); for (String str : myList) { int key = str.length(); if(!byLength.containsKey(key)){ byLength.put(key, new ArrayList ()); } byLength.get(key).add(str); }

Flat Map Do a map and flatten the result by one level // Java 8 Stream chars = myStream.flatMapToInt (s -> s.chars()).mapToObj(i -> (char) i); # Python chars = \ (p for q in ( list(s) for s in source ) for p in q) // Java 7 List chars = new ArrayList (); for (String str : myList) { for(char ch : str.toCharArray()){ chars.add(ch); }

Sorting Example: Sort strings by length (longest to shortest) and then alphabetically Java 8 Stream result = myStream.sorted( Comparator.comparing(String::length).reversed().thenComparing( Comparator.naturalOrder() ) ); Python # Python result = sorted( source, key = lambda s: ( -len(source), source )

Other Stream Methods  Concat  Takes two streams and lazily appends them together  Distinct  Removes duplicate elements  For Each  Perform an operation on each element  Limit  Truncate the stream to a given length  Generate  Create an infinite stream by evaluating a lambda function whenever a new element is requested  Reverse  Reverse the stream  Skip  Remove the first n elements  Zip  Iterate over two streams at the same time

Chaining Stream Methods

Side-by-Side Comparison Imperative  Maintains state.  Manually parallelizable.  More code.  Less intuitive.  Runtime exceptions, like NullPointerException. Functional  Stateless.  Automatically parallelizable.  Less code (usually).  More intuitive.  More errors caught at compile time.

Functional programming is like describing your problem to a mathematician. Imperative programming is like giving instructions to an idiot. —arcus

How to start thinking in the functional style  Avoid “for” loops  If you find yourself using one, there’s probably a better way to do what you want.  Use fewer variables  See if you can connect multiple steps together into an expressive “chain” of method calls.  Avoid “side effects”  When you run a function, it shouldn’t inadvertently change the value of its input or some other variable.

Language Support Languages designed for functional programming  Haskell (1990)  Erlang (1986)  Mathematica (1988)  Elm (2012)  Lisp (1958), including dialects like Clojure (2007) and Scheme (1975) Languages with good functional support  JavaScript (1997)  Java 8 (2014)  C++11 (2011)  Python (1991)  Ruby (1995)  Scala (2003)  Julia :D (2012)

Why has Functional Programming not been more popular in industry?  Lack of Knowledge Base  Most people learn imperative programming first and get comfortable in that programming style  People who’ve never seen the functional programming style before think it’s unreadable  This is starting to change, with more and more schools teaching it in their intro classes (MIT, Yale, UC Berkeley, and others)  Lack of Mainstream Compilers  Functional programming has been around since the ’50s, but has mostly been confined to niche languages like Haskell and Lisp  The JDK added support last year (2014)

Advanced: More on Java 8 Lambda Functions  Not Just One Type  Depending on the relationship between the argument and return types, lambda functions can be one of many types.  To name a few:  Predicate takes a T and returns a boolean  BinaryOperator takes two T’s and returns a T  BiFunction takes a T and a U and returns a V  Lexical Scoping  Lambda functions make a closure over the scope in which there are declared in code, which is common in other languages but is new in Java 8.  Optionals  In order to avoid returning “null” values, Java 8 has a new Optional type, having methods like:  ifPresent( lambda )  orElse( alternate value )

Live Code