Functional Java Lambda Expressions

Similar documents
Binghamton University. CS-140 Fall Functional Java

Binghamton University. CS-140 Fall Functional Java

Functional Programming

Scheme Datatypes. expressions. pairs. atoms. lists. symbols. booleans

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages

Introduction to Functional Programming

CSCE 314 Programming Languages

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Functional Programming. Pure Functional Programming

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CS 314 Principles of Programming Languages

FP Foundations, Scheme

Functional Programming Lecture 1: Introduction

Lambda Calculus. Gunnar Gotshalks LC-1

UMBC CMSC 331 Final Exam

Lecture 16: Static Semantics Overview 1

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

Lambda Calculus LC-1

Functional programming in LISP

Functional Programming and Haskell

Functional Programming. Big Picture. Design of Programming Languages

Class Structure. Prerequisites

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Introduction to Programming (Java) 4/12

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

Introduction to LISP. York University Department of Computer Science and Engineering. York University- CSE V.

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Object Oriented Programming. Java-Lecture 6 - Arrays

PROGRAMMING FUNDAMENTALS

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

CS115 - Module 9 - filter, map, and friends

Introduction to Functional Programming in Java 8

Functional Programming

Lab Instructor : Jean Lai

Advanced Computer Programming

Func%onal Programming in Scheme and Lisp

Lessons on Python Functions

G Programming Languages - Fall 2012

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

CSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point

University of Palestine. Mid Exam Total Grade: 100

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CS 314 Principles of Programming Languages

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CSC 533: Programming Languages. Spring 2015

Func%onal Programming in Scheme and Lisp

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Imperative languages

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides.

LAMBDA EXPRESSIONS AND STREAMS API

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13

CMSC330. Objects, Functional Programming, and lambda calculus

Chapter 11 :: Functional Languages

New Features in Java 8

Structured Programming. Functions and Structured Programming. Functions. Variables

CSE 3302 Programming Languages Lecture 5: Control

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

CS 101 Fall 2005 Midterm 2 Name: ID:

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

Lambda Calculus see notes on Lambda Calculus

Types, Type Inference and Unification

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Introduction to Computer Science Unit 2. Notes

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Make sure the version number is marked on your scantron sheet. This is Version 1

CS 342 Lecture 6 Scheme Procedures and Closures By: Hridesh Rajan

CSc 520 Principles of Programming Languages

CS 242. Fundamentals. Reading: See last slide

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming

CSC 1052 Algorithms & Data Structures II: Lists

Module 10: Imperative Programming, Modularization, and The Future

Symbolic Reasoning. Dr. Neil T. Dantam. Spring CSCI-561, Colorado School of Mines. Dantam (Mines CSCI-561) Symbolic Reasoning Spring / 86

Solutions to Assessment

Lecture content. Course goals. Course Introduction. TDDA69 Data and Program Structure Introduction

Scheme: Expressions & Procedures

Functional Programming and λ Calculus. Amey Karkare Dept of CSE, IIT Kanpur

COS 126 Midterm 1 Written Exam Fall 2011

Pace University. Fundamental Concepts of CS121 1

Chapter 1. Fundamentals of Higher Order Programming

Flow Control. CSC215 Lecture

Vectors in Scheme. Data Structures in Scheme

Introduction to Computer Science Unit 2. Notes

Instructions. This exam has 7 questions, worth 10 points each. You have 50 minutes.

CS 415 Midterm Exam Spring 2002

Comp 333: Concepts of Programming Languages Fall 2016

Fibonacci in Lisp. Computer Programming: Skills & Concepts (CP1) Programming Languages. Varieties of Programing Language

Programming Systems in Artificial Intelligence Functional Programming

functional programming in Python, part 2

Lambda Expressions and Java 8 Streams. Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh. Contents of this talk.

Timing for Interfaces and Abstract Classes

Chapter 8 ( ) Control Abstraction. Subprograms Issues related to subprograms How is control transferred to & from the subprogram?

CIS133J. Working with Numbers in Java

LAMBDA EXPRESSIONS. Summer 2018

public int calculatedamage() { // Generate and return the damage inflicted on ship }

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

Transcription:

Functional Java Lambda Expressions 1

Functions as a First Class Citizen If there was just some way of packaging the compare function And then passing that function as an argument to sort Then we wouldn t need an object We wouldn t need a Comparitor interface We wouldn t need an anonymous inner class or an explicit class We wouldn t need to pass data to the sort method But how can we package a function? 2

Lambda Expressions Invented by Alonzo Church in the 1930 s Method to express an anonymous function Supported in Java 1.8 Simplest form: x -> x*x Parameter name comes first Then -> to indicate this is a lambda expression Then an expression to evaluate the result Can have multiple parameters: (x,y)->x*y Can have multiple statements in braces {} with return 3

History of Lambda Expressions 1956 Information Processing Langauge Allen Newell, Cliff Shaw, and Herbert Siman at RAND/Carnegie IT List processing (dynamic memory, types, recursion, multi-tasking) 1958 LISP John McCarthy at MIT (IBM summer) 2nd major language (after FORTRAN) Mixes data and functions 1970 SCHEME LISP dialect using lambdas Guy Steele & Gerald Sussman at MIT 4

Lambda Concept Provide a way to write a function in Java That does not require a class That does not require a method That can be encapsulated and passed around like data That is not executed right away but can be executed when we are ready Lambda expressions are a way of writing a function Specify parameters Specify a return value 5

Lambda Expression Syntax (argument_list) -> return_expression; argument_list : a comma separated list of variable names Types unspecified! Types are determined when the lambda expression is used return_expression : Any java expression Can use variable(s) from the argument list Expression value is implicitly returned 6

Lambda Expression Extended Syntax (argument_list) ->{ lambda_statements }; argument_list : a comma separated list of variable names Types unspecified! Types are determined when the lambda expression is used lambda_statements : Any java list of statements Can use variable(s) from the argument list Explicit return required 7

How are Lambda Expressions Used? May be used in place of Functional Interfaces interfaces which specify a single method For example Runnable, ActionListener, Comparable See java.util.function in the Java library for generic functional interfaces Of course, we can write our own functional interfaces as well Instead of specifying an object which implements the interface, we can (finally) just specify a lambda expression! 8

Simple Lambda Expression Example public class TestRun { public static void main(string[] args) { Runnable runref = ( ) -> System.out.println("Running runrefs run method"); runref.run( ); } } Running runrefs run method 9

Lambda Expression Comparator Arrays.sort(circles, (arg0, arg1) -> { int retval=0; double area0 = arg0.width*arg0.height; double area1 = arg1.width*arg1.height; if(area0 < area1) retval = -1; else if(area0 > area1) retval = 1; return retval; } ); 10

Simplifying further Why not use the same trick as we used comparing integers? (arg0, arg1) -> arg0.width*arg0.height - arg1.width*arg1.height Problem: Comparators need to return integers 11

Functionalizing Comparisons What if there were a function that maps an object to a number For instance ellipse -> area Reduce comparing objects to comparing numbers The Comparable interface includes static helper methods that use this trick e.g. comparingdouble comparingdouble argument : object which implements the ToDoubleFunction interface ToDoubleFunction interface defines a single method: double applyasdouble(t value) where T is a generic type ToDoubleFunction is a functional interface and may be replaced by a lambda expression! 12

Simplify with comparingdouble Anonymous inner Comparator class: private Comparator<Ellipse2D.Double> comp1 = Comparator.comparingDouble(e-> e.width*e.height); Arrays.sort(circles, comp1); In fact the Comparator object may as well be anonymous: Arrays.sort(circles, Comparator.comparingDouble(e -> e.width*e.height)); 13

Typical functional construct : map map is a function which takes two arguments A function A vector Map applies the function to each element of the vector and computes multiple results The return value of map is a vector of results map *2 [1, 2, 3, 4, 5] [2, 4, 6, 8, 10] 14

Lambda in Other Languages: Scheme Scheme (1975) is a Lisp (1958) dialect > (define (square x) (* x x )) > (map square '(1 2 3 4)) (list 1 4 9 16) Anonymous lambda expression version > (map (lambda (x) (* x x)) '(1 2 3 4)) (list 1 4 9 16) Implementation of Scheme @ http://download.racket-lang.org/ 15

Lambda in other languages: Haskell Haskell (1990) Most popular functional language Put this line in 'Test.hs : square x = x * x Load it with (:l is the load command, l is ell) : :l Test Run: map square [1, 2, 3, 4] [1, 4, 9, 16] or using a lambda expression: map (\x -> x* x) [1, 2, 3, 4] [1, 4, 9, 16] 16

Lambda in Other Languages: Python(3) >>> a= [1,2,3,4] >>> sq = lambda x: x*x >>> list(map(sq,a)) [1, 4, 9, 16] >>> list(map(lambda x:x*x, a)) [1, 4, 9, 16] >>> def squ (n):... return n*n... >>> list(map(squ,a)) [1, 4, 9, 16] 17

Functions as Arguments: C int square ( int x ) { return x * x; } int* map ( int (*f)(int), int len, int array[ ]) { int i = 0; int* ret = (int*)malloc(len*sizeof(int)); for(i = 0; i < len; i++) { ret[i] = (*f)(array[i]); } return ret; } void main () { int arg[ ] = {1, 2, 3, 4}; int* tmp = map(square, 4, arg); printf("[%d, %d, %d, %d]\n", tmp[0], tmp[1], tmp[2], tmp[3]); } 18

Defining map as static method in Java import java.util.function.function; // Java 1.8 Interface: apply method public class Mapper { public static double[ ] map(double[ ] array, Function<Double, Double> fn) { double[ ] temp = null; if(array!= null) { temp = new double[array.length]; for(int i = 0; i < array.length; i++) { temp[i] = fn.apply(array[i]); } } return temp; } } 19

Defining Function to be Passed In an anonymous inner class: static Function<Double, Double> square = new Function<Double, Double>() { @Override public Double apply(double t) { return t*t; } }; As a stand-alone method public static double sqr(double d) { return d*d; } 20

Passing Functions in to Functions public static void main(string[ ] args){ double[] data = {1,2,3,4}; double[] sq1 = Mapper.map(data, square); double[] sq2 = map(data, Mapper::sqr); // Note :: double[] sq3 = map(data, Math::sqrt); // sqrt in Java lib double[] sq4 = map(data, d -> d*d); // lambda } 21

Defining map as a dynamic method import java.util.function.function; // Java 1.8 Interface: apply method public class MapDyn { public double[ ] map(double[ ] array, Function<Double, Double> fn) { double[ ] temp = null; if(array!= null) { temp = new double[array.length]; for(int i = 0; i < array.length; i++) { temp[i] = fn.apply(array[i]); } } } return temp; this is available, but not used 22

Defining Function to be Passed (dyn) In an anonymous inner class: Function<Double, Double> square = this is available, but not used new Function<Double, Double>() { @Override public Double apply(double t) { return t*t; } }; As a stand-alone method public static double sqr(double d) { return d*d; } 23

Passing Functions (dynamic) public static void main(string[ ] args){ need a reference double[] data = {1,2,3,4}; variable to find MapDyn test = new MapDyn(); the map method double[] sq1 = test.map(data, test.square); double[] sq2 = test.map(data, MapDyn::sqr); // Note :: double[] sq3 = test.map(data, Math::sqrt); double[] sq4 = test.map(data, d -> d*d); // lambda } 24