Functional Programming in Java. CSE 219 Department of Computer Science, Stony Brook University

Similar documents
JVM ByteCode Interpreter

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona

Programming language design and analysis

CMSC 330: Organization of Programming Languages. Functional Programming with OCaml

Frege. purely functional programming on the JVM. GOTO Berlin 2015

Die funktionale Zukunft

MEAP Edition Manning Early Access Program The Joy of Kotlin Version 8

Frege. purely functional programming on the JVM. JUG Luzern 2016

Functional Programming in Scala by Paul Chiusana Rúnar Bjarnason

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Side Effects (3A) Young Won Lim 1/13/18

A Summary of Out of the Tar Pit

CSC324 Principles of Programming Languages

Principles of Program Design. What should be taught in core programming curricula

SED 508. Transcript EPISODE 508 [INTRODUCTION]

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Presented By Andrew Butt

Javaslang. Achieve functional eloquence in Java. Blagoj Atanasovski 11/03/2017 1

CS113: Lecture 4. Topics: Functions. Function Activation Records

Refactoring to Functional. Hadi Hariri

D Programming Language

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

Functional Programming and Haskell

Functional Programming. Big Picture. Design of Programming Languages

Synchronization SPL/2010 SPL/20 1

class objects instances Fields Constructors Methods static

Functional Programming Principles in Scala. Martin Odersky

Functional Programming. Ionut G. Stan - OpenAgile 2010

Weeks 6&7: Procedures and Parameter Passing

The Singleton Pattern. Design Patterns In Java Bob Tarr

Functional Programming

Functional Programming in Java Part 2. CSE 219 Department of Computer Science, Stony Brook University

Classes Classes 2 / 36

Higher Order Perl. Finlay Thompson. 14 March 2006

Spring % of course grade

Methods. CSE 114, Computer Science 1 Stony Brook University

Space Exploration EECS /25

Programming Languages and Techniques (CIS120)

BCS THE CHARTERED INSTITUTE FOR IT. BCS Higher Education Qualifications BCS Level 6 Professional Graduate Diploma in IT EXAMINERS' REPORT

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Functional Programming Lecture 13: FP in the Real World

Introduction to Functional Programming in Haskell 1 / 56

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Think like an Elm developer

This exam is open book. Each question is worth 3 points.

CSE 505: Concepts of Programming Languages

Lecture 1 - Introduction (Class Notes)

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #4. Review: Methods / Code

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Computer Components. Software{ User Programs. Operating System. Hardware

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010

DESIGN, EVOLUTION AND USE

Basic Principles of analysis and testing software

Cross-Platform, Functional, Reactive GUIs

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Immutability and Design Patterns in Ruby

Programming Paradigms in Python

Some Advanced ML Features

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Chapter 11 :: Functional Languages

3. Functional Programming. Oscar Nierstrasz

CS 11 Haskell track: lecture 1

Programming Language Pragmatics

Every language has its own scoping rules. For example, what is the scope of variable j in this Java program?

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

CSE 12 Abstract Syntax Trees

The story so far. Elements of Programming Languages. While-programs. Mutable vs. immutable

Testing. CMSC 433 Programming Language Technologies and Paradigms Spring A Real Testing Example. Example (Black Box)?

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Introduction to Functional Programming and Haskell. Aden Seaman

Chapter 4 Defining Classes I

Storing Data in Objects

Generics in Java and Beyond

Lecture 6 Introduction to Objects and Classes

Functional programming in C#

International Journal of Advance Engineering and Research Development. Leaking in Java

Chapter 1 Introduction to Java

The Singleton Pattern. Design Patterns In Java Bob Tarr

An introduction introduction to functional functional programming programming using usin Haskell

Java Bytecode (binary file)

Mutable Data Types. Prof. Clarkson Fall A New Despair Mutability Strikes Back Return of Imperative Programming

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Problem Solving with C++

Test-Driven Development (a.k.a. Design to Test) CSE260, Computer Science B: Honors Stony Brook University

The Object Oriented Paradigm

Course Outline. Introduction to java

CSE373: Data Structure & Algorithms Lecture 23: Programming Languages. Aaron Bauer Winter 2014

Mutable References. Chapter 1

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

CS 351 Design of Large Programs Programming Abstractions

STRUCTURING OF PROGRAM

Functional Programming in C++

Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

! Use of formal notations. ! in software system descriptions. ! for a broad range of effects. ! and varying levels of use. !

Concepts of Programming Languages

Declarative concurrency. March 3, 2014

Detecting and preventing null pointer errors with pluggable type-checking

Transcription:

Functional Programming in Java CSE 219, Stony Brook University

What is functional programming? There is no single precise definition of functional programming (FP) We should think of it as a programming paradigm It is NOT the opposite of object-priented programming. Some FP languages are OO, while others are not It s not a binary choice either. Some language are more FP-friendly than others. We can think of FP as a set of techniques that supplement or replace techniques found elsewhere. For example First class functions Anonymous functions Closures Currying Lazy evaluation Algebraic data types Polymorphism of parameters

What it isn t Functional Programming Imperative Programming Imperative programs are composed of elements that perform some action An action implies an initial state, a final state, and transition from one to the other Strictly imperative programs are described by a series of state transitions Functional programs are composed of elements defined in terms of what they are, not in terms of what they do The main consequence of this is that we can replace an evaluation expression with the corresponding evaluation result

Replacement and Side Effects Consider this example psuedocode for adding two non-negative values a and b: 1. if b == 0 2. return a 3. else 4. increment a 5. derement b 6. goto 1. This is an imperative-style pseudocode Note that the original values are destroyed by this program In Java, this will not happen due to passing by value, so local changes will not have a global effect This kind of a change is a side effect of the program Purely functional programs have no observable side effects Observable, because in practice, programs are written for computers that are not functional. All computers are based on the same imperative paradigm.

Functions Functional programs are built by composing functions that take in a single argument, and return a single value Since computers were designed for imperative programs, functions are treated like black boxes as far as the theory of functional programming is concerned In practice, a lot of imperative-style processes and state transitions happen inside functions, but in a way that no effect is observable from the outside

More on side effects In practice, it is impossible to avoid side effects A program may create an out of memory error, which is a transition to a special error state A program may have some other error and handle it, which is a transition to a special error state and then back from it Threads, etc. So, again, in practice when we talk about functional programs, we mean programs written to have no intentional side effects and as few non-intentional side effects as possible

Referential Transparency Having no intentional observable side effects is just one aspect of functional programming The output of a functional program must only depend on its arguments, and not depend on any other external factors This means functional code may not read data from the console, a file, a database, etc. A code is said to be referentially transparent if it does not cause state changes and does not depend on the external world A referentially transparent expression can be replaced with its corresponding value without changing the program s behavior Referentially transparent codes are far easier for testing, debugging, and formal reasoning

Properties of Referential Transparency Self-contained. Doesn t depend on any external context Deterministic. Always return the same value for the same argument No Exceptions. Will never throw an exception. Runtime exceptions like out of memory error, etc., are due to bugs that need to be fixed, and the imperative part of the program is responsible for this A note on thread-safety Functional programs are inherently thread-safe because they avoid mutation of shared states (which would be an observable side effect). This doesn t mean that all data has to be immutable. But all shared data must be!

Reasoning with substitution public static void main(string[] args) { int x = add(mult(2, 3), mult(4, 5)); public static int add(int a, int b) { System.out.println(String.format("Returning %s as the result of " + %s + %s", a + b, a, b)); return a + b; public static int mult(int a, int b) { return a * b;

A Donut public static Donut buyadonut(creditcard card) { Donut donut = new Donut(); card.charge(donut.price); // observable side effect return donut; // return value The above code returns a donut, but also has an observable side effect This code will be hard to test (unless you can contact the actual bank or use a mockup bank for testing) We are going to convert this simple example into a functional program Which is important because it makes testing a lot easier

A Functional Donut How can we charge the credit card without observable side effects? Represent the charge as a Payment operation We will need buyadonut to return the donut as well as the Payment public class Payment { public final CreditCard creditcard; public final int amount; public Payment(CreditCard creditcard, int amount) { this.creditcard = creditcard; this.amount = amount;

A Functional Donut How can we charge the credit card without observable side effects? Represent the charge as a Payment operation We will need buyadonut to return the donut as well as the Payment How can we return both? public class Payment { public final CreditCard creditcard; public final int amount; public Payment(CreditCard creditcard, int amount) { this.creditcard = creditcard; this.amount = amount;

Advantages of Functional Programming Functional programming is programming with functions and having no side effects Functional programs are easy to reason about and easy to test offer a high level of abstraction and reusability more robust than their imperative counterparts offer better thread-safety because they avoid shared mutable states

First-Class Functions Functions become first-class citizens! pass functions as arguments to other functions return them as the values from other functions assign them to variables store them in data structures Before JDK 1.8 Java kind of had a simulation of this capabiilty to some extent with anonymous classes What all this essentially means is that we can start treating functions as objects in JDK 1.8 and beyond

Functions as Objects More private than private Functions in a class can now be visible to only method in that class Simplification of code in design patterns Higher-order functions Methods that take a function as its formal parameter Or return a function object So the natural question is: how to create these function objects in Java?