Binghamton University. CS-140 Fall Functional Java

Size: px
Start display at page:

Download "Binghamton University. CS-140 Fall Functional Java"

Transcription

1 Functional Java 1

2 First Class Data We have learned how to manipulate data with programs We can pass data to methods via arguments We can return data from methods via return types We can encapsulate data into objects / classes The object can be accessed by its reference variable The object can be acted on by its methods Because we handle data so easily, data is a first class citizen in the Java world 2

3 Functions have been Second Class We know how to define a function, but we don t know (yet) how to manipulate a function Can we pass a function as an argument? Can we return a function as a parameter? How do we encapsulate and reference a function? Closest we come is polymorphism One function invocation invokes different methods 3

4 Examples of Manipulating Functions Starting a GUI, we needed to add a function to the event loop to start things off the createandshowgui method We created an object that was an instance of an anonymous inner class The anonymous inner class implemented the Runnable interface We passed that object to the invokelater method as data The invokelater eventually invoked objref.run() That invoked the run method in our anonymous inner class That invoked the createandshowgui method Whew 4

5 Examples of Manipulating Functions When we registered an actionlistener callback We changed our class to implement the ActionListener interface We added an ActionPerformed method to our class We then registered by invoking addactionlistener The parameter to addactionlistener was not the callback function, but an object (data) The convention is, when an action is performed, find the data registered to that action, and invoke the object.actionperformed method Whew 5

6 Data Orientation When all you have is a hammer, everything looks like a nail When all you have is data, everything looks like an int 6

7 Another example of function We made Account comparable by adding a compareto method Sort uses compareto to determine how two objects in the same class are related (<, =, >) What about a class that does not implement Comparable? What if we could write some code OUTSIDE the class to tell sort how two objects are related? 7

8 Functional Needs We need a function that compares two items, and returns an integer If functions were first class citizens, we could define such a function and send it as an argument Or we could come up with an object whose class has such a function 8

9 The Comparator Interface Used to compare two objects Like ArrayList, supports a generic type Comparator<T> Requires one method int compare(t obj1,t obj2) Reference to the comparator object passed as a parameter to sort When sort has objects A and B, it invokes compobj.compare(a,b) to figure out whether A<B, A==B, or A>B Confused? Let s do an example. 9

10 java.awt.geom.ellipse2d.double An ellipse has fields: x, y, width, and height (x, y) width height Slides 6 10

11 Let s sort arrays of ellipses by area Area = π width height 4 11

12 Make a class that supports comparator import java.awt.geom.ellipse2d; import java.util.comparator; public class MyEllipseComp implements Comparator<Ellipse2D.Double> public int compare(ellipse2d.double arg0, Ellipse2D.Double arg1) { int retval = 0; double area0 = Math.PI*arg0.width*arg0.height/4; double area1 = Math.PI*arg1.width*arg1.height/4; if(area0 < area1) retval = -1; else if(area0 > area1) retval = 1; return retval; 12

13 Simplify remove common factors import java.awt.geom.ellipse2d; import java.util.comparator; public class MyEllipseComp implements Comparator<Ellipse2D.Double> public int compare(ellipse2d.double arg0, Ellipse2D.Double 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; 13

14 Make an array of ellipses (circles) Ellipse2D.Double[ ] circles = { new Ellipse2D.Double(4, 7, 12, 12), new Ellipse2D.Double(5, 11, 16, 16), new Ellipse2D.Double(2, 65, 10, 10), new Ellipse2D.Double(7, 12, 1, 1), new Ellipse2D.Double(12, 6, 15, 15), new Ellipse2D.Double(34, 2, 14, 14) ; 14

15 Sort the array with a comparator Arrays.sort(circles, new MyEllipseComp()); for(ellipse2d e : circles) { System.out.print(e.getWidth() + " "); System.out.println(); Prints:

16 Anonymous Inner Class Why do we need an entire class just for one method? We only need it once to do the sort. Since Java 1.1, we can code an Anonymous Inner Class Anonymous has no name. We are only going to use it once. Inner contained inside another class Use the interface name as the type of the class! 16

17 Example Anonymous Inner Class Comparator<Ellipse2D.Double> comp = new Comparator<Ellipse2D.Double>() public int compare(ellipse2d.double arg0, Ellipse2D.Double 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; Arrays.sort(circles, comp); 17

18 Or, skip the reference variable Arrays.sort(circles, new Comparator<Ellipse2D.Double>() public int compare(ellipse2d.double arg0, Ellipse2D.Double 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; ); 18

19 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? 19

20 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 20

21 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; ); 21

22 Simplifying further Why not use the same trick as we used comparing integers? (arg0, arg1) -> arg0.width*arg0.height - arg1.width*arg1.height Comparators need to return integers The comparator class offers helper functions e.g. comparingdouble Argument a function to extract a double number from object When sort has objects A and B, it will invoke extract function on both, to get double values a and b Then, comparingdouble will return int <0, 0, >0, depending on the sign of (a b) 22

23 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)); 23

24 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 24

25 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] 25

26 Lambda in Other Languages: Scheme Scheme (1975) is a Lisp (1958) dialect > (define (square x) (* x x )) > (map square '( )) (list ) Anonymous lambda expression version > (map (lambda (x) (* x x)) '( )) (list ) Implementation of 26

27 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] 27

28 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] 28

29 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]); 29

30 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; 30

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

32 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 32

33 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 33

34 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>() public Double apply(double t) { return t*t; ; As a stand-alone method public static double sqr(double d) { return d*d; 34

35 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 35

Functional Java Lambda Expressions

Functional Java Lambda Expressions 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

More information

Binghamton University. CS-140 Fall Functional Java

Binghamton University. CS-140 Fall Functional Java Functional Java 1 First Class Data We have learned how to manipulate data with programs We can pass data to methods via arguments We can return data from methods via return types We can encapsulate data

More information

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

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name: CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : If a child overrides

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

Introduction to Functional Programming

Introduction to Functional Programming Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,

More information

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

Scheme Datatypes. expressions. pairs. atoms. lists. symbols. booleans Lisp Lisp was invented in 1958 at MIT by John McCarthy. Lisp stands for list processing. Its intended use was research in artificial intelligence. It is based on the λ calculus which was invented by Alonzo

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell 101 Dr. Hyunyoung Lee 1 Contents 1. Historical Background of Haskell 2. Lazy, Pure, and Functional Language 3. Using ghc and ghci 4. Functions 5. Haskell Scripts

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

Functional Programming

Functional Programming Functional Programming CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario When the Function is the Thing In O-O programming, you typically know where an action is needed,

More information

UMBC CMSC 331 Final Exam

UMBC CMSC 331 Final Exam UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy

More information

FP Foundations, Scheme

FP Foundations, Scheme FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

More information

University of Palestine. Mid Exam Total Grade: 100

University of Palestine. Mid Exam Total Grade: 100 First Question No. of Branches (5) A) Choose the correct answer: 1. If we type: system.out.println( a ); in the main() method, what will be the result? int a=12; //in the global space... void f() { int

More information

Introduction to Functional Programming in Java 8

Introduction to Functional Programming in Java 8 1 Introduction to Functional Programming in Java 8 Java 8 is the current version of Java that was released in March, 2014. While there are many new features in Java 8, the core addition is functional programming

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

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

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name: CS-140 Fall 2018 Test 2 Version A Nov. 12, 2018 Name: 1. (10 points) For the following, Check T if the statement is true, or F if the statement is false. (a) X T F : A class in Java contains fields, and

More information

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

LAMBDA EXPRESSIONS AND STREAMS API

LAMBDA EXPRESSIONS AND STREAMS API Java 8 LAMBDA EXPRESSIONS AND STREAMS API An Introduction Methods As Data 2 @FunctionalInterface public interface Runnable { public abstract void run(); public interface ActionListener extends EventListener

More information

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : An interface defines the list of fields

More information

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

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Basics 2 Contents 1. Jump into Haskell: Using ghc and ghci (more detail) 2. Historical Background of Haskell 3. Lazy, Pure, and Functional

More information

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

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

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming Ernest Ryu UCLA Mathematics Last edited: December 8, 2017 Introductory example When you write an ActionListener for a GUI, you

More information

The return Statement

The return Statement The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return

More information

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

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7 Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

More information

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

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Functional Programming Lecture 1: Introduction

Functional Programming Lecture 1: Introduction Functional Programming Lecture 1: Introduction Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague viliam.lisy@fel.cvut.cz Acknowledgements

More information

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer STUDENT NAME: ID: The exam consists of five questions. There are a total of 10 points. You may use the back

More information

Imperative languages

Imperative languages Imperative languages Von Neumann model: store with addressable locations machine code: effect achieved by changing contents of store locations instructions executed in sequence, flow of control altered

More information

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

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

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

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

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

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc. CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

More information

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

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

CMSC132 Summer 2018 Midterm 1

CMSC132 Summer 2018 Midterm 1 CMSC132 Summer 2018 Midterm 1 First Name (PRINT): Last Name (PRINT): Instructions This exam is a closed-book and closed-notes exam. Total point value is 100 points. The exam is a 80 minutes exam. Please

More information

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff and Arrays Comp Sci 1570 Introduction to C++ Outline and 1 2 Multi-dimensional and 3 4 5 Outline and 1 2 Multi-dimensional and 3 4 5 Array declaration and An array is a series of elements of the same type

More information

Functional Programming

Functional Programming Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

More information

Programming Exercise 7: Static Methods

Programming Exercise 7: Static Methods Programming Exercise 7: Static Methods Due date for section 001: Monday, February 29 by 10 am Due date for section 002: Wednesday, March 2 by 10 am Purpose: Introduction to writing methods and code re-use.

More information

CSE373 Fall 2013, Midterm Examination October 18, 2013

CSE373 Fall 2013, Midterm Examination October 18, 2013 CSE373 Fall 2013, Midterm Examination October 18, 2013 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, closed calculator, closed electronics. Please stop

More information

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226 Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters

More information

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics 1 Collections (from the Java tutorial)* A collection (sometimes called a container) is simply an object that

More information

Topic 7: Algebraic Data Types

Topic 7: Algebraic Data Types Topic 7: Algebraic Data Types 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.5, 5.7, 5.8, 5.10, 5.11, 5.12, 5.14 14.4, 14.5, 14.6 14.9, 14.11,

More information

Functional programming in LISP

Functional programming in LISP Programming Languages Week 4 Functional programming in LISP College of Information Science and Engineering Ritsumeikan University review of part 3 enumeration of dictionaries you receive a sequence of

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Programming by Delegation

Programming by Delegation Chapter 2 a Programming by Delegation I. Scott MacKenzie a These slides are mostly based on the course text: Java by abstraction: A client-view approach (4 th edition), H. Roumani (2015). 1 Topics What

More information

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

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Introduction to C Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Problem: Too Many Details For example: Lab 7 Bubble Sort Needed to keep track of too many details! Outer Loop When do

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

CMSC330. Objects, Functional Programming, and lambda calculus

CMSC330. Objects, Functional Programming, and lambda calculus CMSC330 Objects, Functional Programming, and lambda calculus 1 OOP vs. FP Object-oriented programming (OOP) Computation as interactions between objects Objects encapsulate mutable data (state) Accessed

More information

Points Missed on Page page 1 of 8

Points Missed on Page page 1 of 8 Midterm II - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total. Name: ID: Problem #1 (8 points) Rewrite the following code segment using a for loop instead of a while loop (that is

More information

Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

More information

Java Programming. Abstract classes and Interfaces

Java Programming. Abstract classes and Interfaces Java Programming Abstract classes and Interfaces Classes A class is composed of data methods public class Rectangle { private double width, height; public Rectangle(double width, double height) { this.width=

More information

Today. Reading. Homework. Lecture Notes CPSC 224 (Spring 2012) hashcode() method. Collections class. Ch 9: hw 7 out (due in a week)

Today. Reading. Homework. Lecture Notes CPSC 224 (Spring 2012) hashcode() method. Collections class. Ch 9: hw 7 out (due in a week) Today hashcode() method Collections class Reading Ch 9: 406-424 Homework hw 7 out (due in a week) S. Bowers 1 of 9 The Object hashcode() function The signature: public int hashcode() What it does: returns

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice Name Section Number CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice All Sections Bob Wilson OPEN BOOK / OPEN NOTES: You will have all 90 minutes until the start of the next class period.

More information

Binghamton University. CS-140 Fall Dynamic Types

Binghamton University. CS-140 Fall Dynamic Types Dynamic Types 1 Assignment to a subtype If public Duck extends Bird { Then, you may code:. } Bird bref; Duck quack = new Duck(); bref = quack; A subtype may be assigned where the supertype is expected

More information

Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Topic 5: Higher Order Functions

Topic 5: Higher Order Functions Topic 5: Higher Order Functions 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7, 10.8, 10.9, 10.10,

More information

Topic 5: Higher Order Functions

Topic 5: Higher Order Functions Topic 5: Higher Order Functions 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7, 10.8, 10.9, 10.10,

More information

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting Overview ITI 1121. Introduction to Computing II Rafael Falcon and Marcel Turcotte (with contributions from R. Holte) Electrical Engineering and Computer Science University of Ottawa Interface Abstract

More information

Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

More information

Class Structure. Prerequisites

Class Structure. Prerequisites Class Structure Procedural abstraction and recursion 6.037 - Structure and Interpretation of Computer Programs Mike Phillips, Benjamin Barenblat, Leon Shen, Ben Vandiver, Alex Vandiver, Arthur Migdal Massachusetts

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

Week 7. Statically-typed OO languages: C++ Closer look at subtyping C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

More information

CMSC132 Summer 2018 Midterm 1. Solution

CMSC132 Summer 2018 Midterm 1. Solution CMSC132 Summer 2018 Midterm 1 Solution First Name (PRINT): Last Name (PRINT): Instructions This exam is a closed-book and closed-notes exam. Total point value is 100 points. The exam is a 80 minutes exam.

More information

Last time s big ideas

Last time s big ideas Last time s big ideas 1. When we want an array of objects, we store their references in the array 2. It is important to distinguish between the specification and implementation of a class 3. public and

More information

CS 415 Midterm Exam Spring 2002

CS 415 Midterm Exam Spring 2002 CS 415 Midterm Exam Spring 2002 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Good Luck! Score Fortran Algol 60 Compilation Names, Bindings, Scope Functional Programming

More information

Outline HW2. Feedback. CS1007: Object Oriented Design and Programming in Java

Outline HW2. Feedback. CS1007: Object Oriented Design and Programming in Java Outline CS1007: Object Oriented Design and Programming in Java Lecture #8 Oct 4 Shlomo Hershkop shlomo@cs.columbia.edu Unit Testing Sorting Algorithms Polymorphism Interfaces Basic graphics Layout managers

More information

CIS133J. Working with Numbers in Java

CIS133J. Working with Numbers in Java CIS133J Working with Numbers in Java Contents: Using variables with integral numbers Using variables with floating point numbers How to declare integral variables How to declare floating point variables

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

Lambda Calculus see notes on Lambda Calculus

Lambda Calculus see notes on Lambda Calculus Lambda Calculus see notes on Lambda Calculus Shakil M. Khan adapted from Gunnar Gotshalks recap so far: Lisp data structures basic Lisp programming bound/free variables, scope of variables Lisp symbols,

More information

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

CSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point Lambda Calculus CSE 505 Lecture #9 October 1, 2012 Expr ::= Var λ Var. Expr (Expr Expr) Key Concepts: Bound and Free Occurrences Substitution, Reduction Rules: α, β, η Confluence and Unique Normal Form

More information

CS 180 Final Exam Review 12/(11, 12)/08

CS 180 Final Exam Review 12/(11, 12)/08 CS 180 Final Exam Review 12/(11, 12)/08 Announcements Final Exam Thursday, 18 th December, 10:20 am 12:20 pm in PHYS 112 Format 30 multiple choice questions 5 programming questions More stress on topics

More information

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario The Story So Far... Classes as collections of fields and methods. Methods can access fields, and

More information

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 6: Arrays Arrays An array is an ordered list of values Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking The

More information

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

Introduction to LISP. York University Department of Computer Science and Engineering. York University- CSE V. Introduction to LISP York University Department of Computer Science and Engineering York University- CSE 3401- V. Movahedi 11_LISP 1 Introduction to LISP Evaluation and arguments S- expressions Lists Numbers

More information

Lecture Set 4: More About Methods and More About Operators

Lecture Set 4: More About Methods and More About Operators Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static

More information

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

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

More information

COMP6700/2140 Code as Data

COMP6700/2140 Code as Data COMP6700/2140 Code as Data Alexei B Khorev Research School of Computer Science, ANU March 2017 Alexei B Khorev (RSCS, ANU) COMP6700/2140 Code as Data March 2017 1 / 19 Topics 1 What does treating code

More information

LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.

LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. LISP Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. From one perspective, sequences of bits can be interpreted as a code for ordinary decimal digits,

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Methods and Data (Savitch, Chapter 5)

Methods and Data (Savitch, Chapter 5) Methods and Data (Savitch, Chapter 5) TOPICS Invoking Methods Return Values Local Variables Method Parameters Public versus Private 2 public class Temperature { public static void main(string[] args) {

More information

EECS 1001 and EECS 1030M, lab 01 conflict

EECS 1001 and EECS 1030M, lab 01 conflict EECS 1001 and EECS 1030M, lab 01 conflict Those students who are taking EECS 1001 and who are enrolled in lab 01 of EECS 1030M should switch to lab 02. If you need my help with switching lab sections,

More information

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals

More information

Midterm Solutions. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Midterm Solutions. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Midterm Solutions Instructor: Scott Kristjanson CMP 125/125 SU Burnaby, all 2013 2 Question 1 1 Mark if checked something that should be checked 1 Mark if left unchecked, something that should not be checked

More information

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts COMP519 Web Programming Lecture 21: Python (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Functions

More information

Tool-assisted spec development

Tool-assisted spec development Typed Clojure Tool-assisted spec development Ambrose Bonnaire-Sergeant Sam Tobin-Hochstadt Spec is awesome Expressive specification language Runtime instrumentation Generative testing Documentation Parsing

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

COMP110 MT2 Study Guide

COMP110 MT2 Study Guide COMP110 MT2 Study Guide 1. T/F Determine whether the following statements are true or false. If false, correct the statement. F a. Given a list of unsorted integers from 0 to 100, inclusive, we can perform

More information

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

More information

Ausblick auf Java 8. Martin Plümicke. 25. Mai Baden-Wuerttemberg Cooperative State University Stuttgart/Horb

Ausblick auf Java 8. Martin Plümicke. 25. Mai Baden-Wuerttemberg Cooperative State University Stuttgart/Horb Ausblick auf Java 8 Martin Plümicke Baden-Wuerttemberg Cooperative State University Stuttgart/Horb 25. Mai 2012 Overview Introduction Introduction Closures Java s motivation λ expressions Functional interfaces

More information

Final Exam. COMP Summer I June 26, points

Final Exam. COMP Summer I June 26, points Final Exam COMP 14-090 Summer I 2000 June 26, 2000 200 points 1. Closed book and closed notes. No outside material allowed. 2. Write all answers on the test itself. Do not write any answers in a blue book

More information

Seminar on Languages for Scientific Computing Aachen, 6 Feb Navid Abbaszadeh.

Seminar on Languages for Scientific Computing Aachen, 6 Feb Navid Abbaszadeh. Scientific Computing Aachen, 6 Feb 2014 navid.abbaszadeh@rwth-aachen.de Overview Trends Introduction Paradigms, Data Structures, Syntax Compilation & Execution Concurrency Model Reference Types Performance

More information

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

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

More information

Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89

Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89 Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic expressions. Symbolic manipulation: you do it all the

More information