Lecture 2: Design and Implementation of Lambda Expressions in Java 8 Alfred V. Aho CS E6998-1: Advanced Topics in Programming Languages.

Slides:



Advertisements
Similar presentations
Introduction to Compilation of Functional Languages Wanhe Zhang Computing and Software Department McMaster University 16 th, March, 2004.
Advertisements

Arrays.
Spring Semester 2013 Lecture 5
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Introduction to C Programming
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Remote Procedure Call in SR Programming Language By Tze-Kin Tsang 3/20/2000.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
Programming II Object Oriented Programming with Java - Advanced Topics - Java 8: Functional Interfaces, Method References and Lambda Expressions Alastair.
Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.
Introduction to Methods
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
1 COMP313A Functional Programming (1). 2 Main Differences with Imperative Languages Say more about what is computed as opposed to how Pure functional.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
1 Introduction Modules  Most computer programs solve much larger problem than the examples in last sessions.  The problem is more manageable and easy.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Utilities (Part 2) Implementing static features 1.
Programming in Java CSCI-2220 Object Oriented Programming.
SE-1010 Dr. Mark L. Hornick 1 Java Programming Basics.
TIVDM2Functional Programming Language Concepts 1 Concepts from Functional Programming Languages Peter Gorm Larsen.
Lambda Expressions Version 1.0
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CS 261 – Data Structures Introduction to C Programming.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
Java8 Released: March 18, Lambda Expressions.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Methods.
Haskell Introduction CSCE 314 Spring CSCE 314 – Programming Studio Historical Background 1930s: Alonzo Church develops the lambda calculus, a simple.
JAVA 8 AND FUNCTIONAL PROGRAMMING. What is Functional Programming?  Focus on Mathematical function computations  Generally don’t think about “state”
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Functional Processing of Collections (Advanced) 6.0.
1 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Functional Programming
Functional Programming
Information and Computer Sciences University of Hawaii, Manoa
Advanced Java Programming 51037
Taking Java from purely OOP by adding “functional level Programming”
Java Primer 1: Types, Classes and Operators
Principles of programming languages 4: Parameter passing, Scope rules
Functional Processing of Collections (Advanced)
Java Algorithms.
Functional Programming with Java
Java 8 Java 8 is the biggest change to Java since the inception of the language Lambdas are the most important new addition Java is playing catch-up: most.
Chapter 6 Methods: A Deeper Look
COS 260 DAY 10 Tony Gauvin.
Introducing Arrays Array is a data structure that represents a collection of the same types of data.
Group Status Project Status.
Functional interface.
Computer Science 312 What’s New in Java 8? 1.
„Lambda expressions, Optional”
Corresponds with Chapter 5
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Lecture 2: Design and Implementation of Lambda Expressions in Java 8 Alfred V. Aho CS E6998-1: Advanced Topics in Programming Languages and Compilers September 15, 2014

Outline 1.What is the lambda calculus? 2.What is functional programming? 3.What are the benefits of functional programming? 4.Functional programming in Java 8 5.Java 8 lambda expressions 6.Implementation of Java 8 lambda expressions 7.Streams

The Lambda Calculus The lambda calculus was introduced in the 1930s by Alonzo Church as a mathematical system for defining computable functions. The lambda calculus is equivalent in definitional power to that of Turing machines. The lambda calculus serves as the computational model underlying functional programming languages such as Lisp, Haskell, and Ocaml. Features from the lambda calculus such as lambda expressions have been incorporated into many widely used programming languages like C++ and now very recently Java 8.

What is the Lambda Calculus? The central concept in the lambda calculus is an expression generated by the following grammar which can denote a function definition, function application, variable, or parenthesized expression: expr → λ var. expr | expr expr | var | (expr) We can think of a lambda-calculus expression as a program which when evaluated by beta-reductions returns a result consisting of another lambda- calculus expression.

Example of a Lambda Expression The lambda expression λ x. (+ x 1) 2 represents the application of a function λ x. (+ x 1) with a formal parameter x and a body + x 1 to the argument 2. Notice that the function definition λ x. (+ x 1) has no name; it is an anonymous function. In Java 8, we would represent this function definition by the Java 8 lambda expression x -> x + 1.

More Examples of Java 8 Lambdas A Java 8 lambda is basically a method in Java without a declaration usually written as (parameters) -> { body }. Examples, 1.(int x, int y) -> { return x + y; } 2.x -> x * x 3.( ) -> x A lambda can have zero or more parameters separated by commas and their type can be explicitly declared or inferred from the context. Parenthesis are not needed around a single parameter. ( ) is used to denote zero parameters. The body can contain zero or more statements. Braces are not needed around a single-statement body.

What is Functional Programming? A style of programming that treats computation as the evaluation of mathematical functions Eliminates side effects Treats data as being immutable Expressions have referential transparency Functions can take functions as arguments and return functions as results Prefers recursion over explicit for-loops

Why do Functional Programming? Allows us to write easier-to-understand, more declarative, more concise programs than imperative programming Allows us to focus on the problem rather than the code Facilitates parallelism

Java 8 Java 8 is the biggest change to Java since the inception of the language Lambdas are the most important new addition Java is playing catch-up: most major programming languages already have support for lambda expressions A big challenge was to introduce lambdas without requiring recompilation of existing binaries

Benefits of Lambdas in Java 8 Enabling functional programming Writing leaner more compact code Facilitating parallel programming Developing more generic, flexible and reusable APIs Being able to pass behaviors as well as data to functions

Java 8 Lambdas Syntax of Java 8 lambda expressions Functional interfaces Variable capture Method references Default methods

Example 1: Print a list of integers with a lambda List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x)); x -> System.out.println(x) is a lambda expression that defines an anonymous function with one parameter named x of type Integer

Example 2: A multiline lambda List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> { x += 2; System.out.println(x); }); Braces are needed to enclose a multiline body in a lambda expression.

Example 3: A lambda with a defined local variable List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> { int y = x * 2; System.out.println(y); }); Just as with ordinary functions, you can define local variables inside the body of a lambda expression

Example 4: A lambda with a declared parameter type List intSeq = Arrays.asList(1,2,3); intSeq.forEach((Integer x -> { x += 2; System.out.println(x); }); You can, if you wish, specify the parameter type.

Implementation of Java 8 Lambdas The Java 8 compiler first converts a lambda expression into a function It then calls the generated function For example, x -> System.out.println(x) could be converted into a generated static function public static void genName(Integer x) { System.out.println(x); } But what type should be generated for this function? How should it be called? What class should it go in?

Functional Interfaces Design decision: Java 8 lambdas are assigned to functional interfaces. A functional interface is a Java interface with exactly one non-default method. E.g., public interface Consumer { void accept(T t); } The package java.util.function defines many new useful functional interfaces.

Assigning a Lambda to a Local Variable public interface Consumer { void accept(T t); } void forEach(Consumer action { for (Integer i:items) { action.accept(t); } List intSeq = Arrrays.asList(1,2,3); Consumer cnsmr = x -> System.out.println(x); intSeq.forEach(cnsmr);

Properties of the Generated Method The method generated from a Java 8 lambda expression has the same signature as the method in the functional interface The type is the same as that of the functional interface to which the lambda expression is assigned The lambda expression becomes the body of the method in the interface

Variable Capture Lambdas can interact with variables defined outside the body of the lambda Using these variables is called variable capture

Local Variable Capture Example public class LVCExample { public static void main(String[] args) { List intSeq = Arrays.asList(1,2,3); int var = 10; intSeq.forEach(x -> System.out.println(x + var)); } Note: local variables used inside the body of a lambda must be final or effectively final

Static Variable Capture Example public class SVCExample { private static int var = 10; public static void main(String[] args) { List intSeq = Arrays.asList(1,2,3); intSeq.forEach(x -> System.out.println(x + var)); }

Method References Method references can be used to pass an existing function in places where a lambda is expected The signature of the referenced method needs to match the signature of the functional interface method

Summary of Method References Method Reference Type SyntaxExample staticClassName::StaticMethodNameString::valueOf constructorClassName::newArrayList::new specific object instance objectReference::MethodNamex::toString arbitrary object of a given type ClassName::InstanceMethodNameObject::toString

Conciseness with Method References We can rewrite the statement intSeq.forEach(x -> System.out.println(x)); more concisely using a method reference intSeq.forEach(System.out::println);

Default Methods Java 8 uses lambda expressions and default methods in conjunction with the Java collections framework to achieve backward compatibility with existing published interfaces For a full discussion see Brian Goetz, Lambdas in Java: A peek under the hood.

Stream API The new java.util.stream package provides utilities to support functional-style operations on streams of values. A common way to obtain a stream is from a collection: Stream stream = collection.stream(); Streams can be sequential or parallel. Streams are useful for selecting values and performing actions on the results.

Stream Operations An intermediate operation keeps a stream open for further operations. Intermediate operations are lazy. A terminal operation must be the final operation on a stream. Once a terminal operation is invoked, the stream is consumed and is no longer usable.

Example Intermediate Operations filter excludes all elements that don’t match a Predicate. map performs a one-to-one transformation of elements using a Function.

A Stream Pipeline A stream pipeline has three components: 1.A source such as a Collection, an array, a generator function, or an IO channel; 2.Zero or more intermediate operations; and 3.A terminal operation

Stream Example int sum = widgets.stream().filter(w -> w.getColor() == RED).mapToInt(w -> w.getWeight()).sum(); Here, widgets is a Collection. We create a stream of Widget objects via Collection.stream(), filter it to produce a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget. Then this stream is summed to produce a total weight. From Java Docs Interface Stream

Parting Example: Using lambdas and stream to sum the squares of the elements on a list List list = Arrays.asList(1,2,3); int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get(); System.out.println(sum); Here map(x -> x*x) squares each element and then reduce((x,y) -> x + y) reduces all elements into a single number

References A lot of the material in this lecture is discussed in much more detail in these informative references: The Java Tutorials, Lambda Expressions, pressions.html Adib Saikali, Java 8 Lambda Expressions and Streams, Brian Goetz, Lambdas in Java: A peek under the hood.