Matching & more list functions

Size: px
Start display at page:

Download "Matching & more list functions"

Transcription

1

2 Matching & more list functions Dan S. Wallach and Mack Joyner, Rice University Copyright 2016 Dan Wallach, All Rights Reserved

3 When you do the same thing over and over If statements start to get ugly If empty-list then XXX else YYY If tree-leaf then XXX else YYY What if you forget a case? Weird bugs crop up. Hard to fix.

4 Wednesday s ogenerate v1 static <T> IList<T> ogenerate(supplier<option<t>> supplier) { Option<T> oresult = supplier.get(); if (oresult.issome()) { return make(oresult.get(), () -> ogenerate(supplier)); else { return makeempty(); This if / then / else block is easy to get wrong. Easy to forget a case. The call to oresult.get() would throw an exception if you got it backwards.

5 Wednesday s ogenerate v2 static <T> IList<T> ogenerate(supplier<option<t>> supplier) { return supplier.get().map(result -> make(result, () -> ogenerate(supplier))).getorelse(makeempty()); This map / getorelse pattern is just another way of writing an if / then / else block. Better than v1 because you won t call get() on an Option.none.

6 The War on IfStatements!

7 Traditional solution: methods in subclasses List.Cons.limit: public IList<T> limit(int n) { if (n < 1) { return makeempty(); return make(headval, tailval.limit(n - 1)); List.Empty.limit (actually IList.Empty.limit): default IList<T> limit(int n) { return this;

8 Traditional solution: methods in subclasses List.Cons.limit: public IList<T> limit(int n) { if (n < 1) { return makeempty(); return make(headval, tailval.limit(n - 1)); Cleverly moving common logic for empty List and LazyList into a single interface that both can share. Don t repeat yourself! List.Empty.limit (actually IList.Empty.limit): default IList<T> limit(int n) { return this;

9 Problems with the subclass approach 1) Related program logic spread across the program Totally different files have code that implements IList.limit() What if you change it one place and forget to change the other? 2) You can t always add new code to somebody else s classes You can t edit the core java.util packages. Your patches to other libraries might not be taken by the maintainer.

10 Pre-Java8 solution: The Visitor Pattern Hypothetical code inside IList<T>: interface IVisitor<T,U> { U acceptnonempty(ilist<t> list); U acceptempty(ilist<t> list); ; default <U> U visit(ivisitor<t,u> visitor) { if(empty()) return visitor.acceptempty(this); else return visitor.acceptnonempty(this); IVisitor defines two methods: acceptempty and acceptnonempty The user creates a whole new class with these two methods defined.

11 Visitor pattern usage Create an anonymous inner class with two method bodies Here s a recursive list-length function, implemented outside of IList: static <T> int listlength(ilist<t> inputlist) { return inputlist.visit(new IVisitor<T, Integer>() public Integer acceptnonempty(ilist<t> list) { return 1 + public Integer acceptempty(ilist<t> list) { return 0; );

12 Visitor pattern usage Create an anonymous inner class with two method bodies Here s a recursive list-length function, implemented outside of IList: static <T> int listlength(ilist<t> inputlist) { return inputlist.visit(new IVisitor<T, Integer>() public Integer acceptnonempty(ilist<t> list) { return 1 + listlength(list.tail()); Anonymous inner classes don t names, they just implement an interface. public Integer acceptempty(ilist<t> list) { return 0; );

13 Visitor pattern usage Create an anonymous inner class with two method bodies Here s a recursive list-length function, implemented outside of IList: static <T> int listlength(ilist<t> inputlist) { return inputlist.visit(new IVisitor<T, Integer>() public Integer acceptnonempty(ilist<t> list) { return 1 + public Integer acceptempty(ilist<t> list) { Standard recursive call. ); return 0;

14 Visitor pattern usage Create an anonymous inner class with two method bodies Here s a recursive list-length function, implemented outside of IList: static <T> int listlength(ilist<t> inputlist) { return inputlist.visit(new IVisitor<T, Integer>() public Integer acceptnonempty(ilist<t> list) { return 1 + public Integer acceptempty(ilist<t> list) { return 0; Bug opportunity: inputlist vs. list say the wrong thing and get ); the wrong answer. (Anonymous inner classes capture variables just like lambdas.)

15 Pluses / minuses of the Visitor pattern Code for both cases is side-by-side Easier to see all at once, convince yourself it s correct. Method arguments are the correct type. And method names are descriptive of the cases. You can t forget a case. You re required to write two methods for this visitor interface. You don t need to be inside IList or the List class Visitor pattern is general-purpose, useful for all kinds of things. - Ugly, ugly, ugly! IntelliJ at least will write a lot of the boilerplate for you.

16 Java8 solution: matching Actual code in IList; you can use this today: default <Q> Q match(function<ilist<t>, Q> emptyfunc, BiFunction<T, IList<T>, Q> nonemptyfunc) { if (empty()) { return emptyfunc.apply(this); else { return nonemptyfunc.apply(head(), tail()); Two lambdas: one for empty-list, one for non-empty lists No anonymous inner classes, no visitor interface

17 Same example: recursive list-length But now with lambdas! static <T> int listlength(ilist<t> list) { return list.match( emptylist -> 0, (head, tail) -> 1 + listlength(tail));

18 Same example: recursive list-length But now with lambdas! static <T> int listlength(ilist<t> list) { return list.match( emptylist -> 0, (head, tail) -> 1 + listlength(tail)); Deconstruction : The head and tail are given to us already.

19 Same example: recursive list-length But now with lambdas! static <T> int listlength(ilist<t> list) { return list.match( emptylist -> 0, (head, tail) -> 1 + listlength(tail)); Standard recursive call.

20 Which looks better to you? Java7 visitors: Java8 matching with lambdas: static <T> int listlength(ilist<t> input) { return input.visit(new IVisitor<T, Integer>() public Integer acceptnonempty(ilist<t> list) { return 1 + public Integer acceptempty(ilist<t> list) { return 0; ); static <T> int listlength(ilist<t> list) { return list.match( emptylist -> 0, (head, tail) -> 1 + listlength(tail));

21 Which looks better to you? Java7 visitors: Java8 matching with lambdas: static <T> int listlength(ilist<t> input) { return input.visit(new IVisitor<T, Integer>() public Integer acceptnonempty(ilist<t> list) { return 1 + public Integer acceptempty(ilist<t> list) { return 0; ); static <T> int listlength(ilist<t> list) { return list.match( emptylist -> 0, (head, tail) -> 1 + listlength(tail)); λ

22 If you ever use a real functional language The matching features are typically built into the language And you can match deeply into the list Scala example: if you want to match a list with at least two elements: result = list match { case List(val1, List(val2, tail)) =>... case... Neither Java7 visitors nor our Java8 matching can do this. Take Comp311 and you ll get to do this and more.

23 If you ever use a real functional language The matching features are typically built into the language And you can match deeply into the list Scala example: if you want to match a list with at least two elements: result = list match { case List(val1, List(val2, tail)) =>... case... Not in Java Neither Java7 visitors nor our Java8 matching can do this. Take Comp311 and you ll get to do this and more.

24 But we can still do really useful things Here s an example from next week: measure maximum tree depth A tree is either an empty-tree, or a node (element, left-tree, right-tree) default int maxdepth() { return match( emptytree -> 0, (elem, lefttree, righttree) -> Integer.max(leftTree.maxDepth(), righttree.maxdepth()) + 1); Each lambda takes different arguments, deconstructs the tree If you get the order of the lambdas wrong, it won t compile (a feature!)

25 Wednesday s ogenerate" v3 static <T> IList<T> ogenerate(supplier<option<t>> supplier) { return supplier.get().match( () -> makeempty(), result -> make(result, () -> ogenerate(supplier))); Option also has a match method!

26 Wednesday s ogenerate" v3 static <T> IList<T> ogenerate(supplier<option<t>> supplier) { return supplier.get().match( LazyList::makeEmpty, result -> make(result, () -> ogenerate(supplier))); Option also has a match method! () -> LazyList.makeEmpty() LazyList::makeEmpty equivalent code

27 So start using the match methods! You have them this week in IList and Option. Use match rather than if/then/else when writing your Queue methods Finish sooner, fewer bugs, cleaner code

28 A brief note about multiple inheritance

29 Implementing multiple interfaces You ll notice code like this (List.Empty and LazyList.Empty): class Empty<T> implements List<T>, IList.Empty<T> { See how it s implementing more than one interface? You can bring in default methods from more than one place! Not possible in Java7 (This is why we re not doing class inheritance much in Comp215.)

30 Diamond dependencies C++ hackers complain about multiple inheritance. Java does better. interface A { default void foo() { System.out.println("A"); interface B extends A { default void foo() { System.out.println("B"); interface C extends A {... // no mention of foo() class D implements B, C {... foo(); // Does this print A, B, or get a compiler error?

31 Diamond dependencies C++ hackers complain about multiple inheritance. Java does better. interface A { default void foo() { System.out.println("A"); interface B extends A { default void foo() { System.out.println("B"); interface C extends A {... // no mention of foo() class D implements B, C {... foo(); // Does this print A, B, or get a compiler error? The rules: If two interfaces provide the same default method directly? Compiler error. Else, closest definition wins. Disambiguation: Name the one you want. A.super.foo() B.super.foo()

32 When should I use default methods? First write an interface with no code, only method signatures. Make sure it makes sense. Write the class(es) that implement it. Hide the constructors, use factory methods (make, makeempty, etc.) Zen programming rule #1: don t repeat yourself If you have identical code across two classes: Promote it to a default method on the interface Requires that you only use other methods on the interface Cannot see member variables directly

33 Default methods + match When you ve got one liners, match is your friend public interface IList<T> { default Option<T> ohead() { return match( emptylist -> Option.none(), (head, tail) -> Option.some(head)); Keep it simple, keep it all in one place When in doubt, do whatever makes your code cleanest.

34 Cool features in this week s IList / List / LazyList classes

35 IList.nth You can pretend that a list is like an array and fetch something. IList<String> names = List.of("Alice","Bob","Charlie","Dorothy"); assertequals("alice", names.nth(0)); assertequals("bob", names.nth(1)); assertequals("charlie", names.nth(2)); This costs O(n), so if you do it a lot, your performance will suffer.

36 IList.join You can convert a list to a string, joined with any delimiter This shows up all the time, so it s worth having it built-in. This will call the tostring method on each element Works on lists of any type, not just IList<String>! IList<String> names = List.of("Alice","Bob","Charlie","Dorothy"); assertequals("alice:bob:charlie:dorothy", names.join(":"));

37 IList.sublist You can extract a range of a list IList<String> names = List.of("Alice","Bob","Charlie","Dorothy"); assertequals("alice Bob", names.sublist(0,1).join(" ")); assertequals("charlie Dorothy", names.sublist(2,3).join(" "));

38 IList.toString Lists know how to convert themselves to strings Special handling of String (adding quotation marks) Other Comp215 classes, like Option, also have tostring methods IList<Option<String>> list = List.of( Option.some("Alice"), Option.some("Bob"), Option.none(), Option.some("Charlie")); System.out.println(list); Prints this: List(Option.Some("Alice"), Option.Some("Bob"), Option.None(), Option.Some("Charlie"))

39 Hint for this week s ListQueue project Your ListQueue includes a tostring method as well public String tostring() { return "Queue(" + tolazylist().map(strings::objecttoescapedstring).join(", ") + ")"; Maybe you might want to add another method to show the internals Then add logging (not just System.out.println) Watch your queues evolve!

40 Hint for this week s ListQueue project Your ListQueue includes a tostring method as well public String tostring() { return "Queue(" + tolazylist().map(strings::objecttoescapedstring).join(", ") + ")"; Maybe you might want to add another method to show the internals Then add logging (not just System.out.println) Watch your queues evolve! Helper function: put quotation marks around a string properly

Comp215: More lists. Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved.

Comp215: More lists. Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. Comp215: More lists Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. What s a good list interface We now have two different kinds of lists: lazy and eager. (We ll talk

More information

Lambdas and Generics (Intro)

Lambdas and Generics (Intro) Lambdas and Generics (Intro) Dan S. Wallach and Mack Joiner, Rice University Copyright 2016 Dan S. Wallach, All Rights Reserved New this week in Subversion! week02-lists (check it out!) edu/rice/week2lists/glist.java

More information

Comp215: Thinking Generically

Comp215: Thinking Generically Comp215: Thinking Generically Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. Functional APIs On Wednesday, we built a list of Objects. This works. But it sucks. class

More information

Thinking Functionally

Thinking Functionally Thinking Functionally Dan S. Wallach and Mack Joyner, Rice University Copyright 2016 Dan S. Wallach, All Rights Reserved Reminder: Fill out our web form! Fill this out ASAP if you haven t already. http://goo.gl/forms/arykwbc0zy

More information

Lecture 5: Implementing Lists, Version 1

Lecture 5: Implementing Lists, Version 1 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 5: Implementing Lists, Version 1 Contents 1 Implementing Lists 1 2 Methods 2 2.1 isempty...........................................

More information

Welcome to Comp215: Introduction to Program Design

Welcome to Comp215: Introduction to Program Design Welcome to Comp215: Introduction to Program Design Dan S. Wallach and Mack Joyner, Rice University Copyright 2016 Dan S. Wallach, All Rights Reserved Welcome, welcome! Java (really Java8) Recursion and

More information

Comp215: Trees. Mack Joyner and Dan S. Wallach (Rice University) Copyright 2016, Dan S. Wallach. All rights reserved.

Comp215: Trees. Mack Joyner and Dan S. Wallach (Rice University) Copyright 2016, Dan S. Wallach. All rights reserved. Comp215: Trees Mack Joyner and Dan S. Wallach (Rice University) Copyright 2016, Dan S. Wallach. All rights reserved. Trees Sometimes, a list isn t good enough Array List Binary Tree Hash Table Insert O(1)

More information

Comp215: Enums / Testing

Comp215: Enums / Testing Comp215: Enums / Testing Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. edu.rice.regex.namedmatcher You first write something like this: enum TokenType implements

More information

Comp215: Trees. Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved.

Comp215: Trees. Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. Comp215: Trees Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. Trees Sometimes, a list isn t good enough Array List Binary Tree Hash Table Insert O(1) unordered O(n)

More information

16 Multiple Inheritance and Extending ADTs

16 Multiple Inheritance and Extending ADTs Object-Oriented Design Lecture 16 CS 3500 Fall 2009 (Pucella) Tuesday, Nov 10, 2009 16 Multiple Inheritance and Extending ADTs We looked last time at inheritance and delegation as two ways to reuse implementation

More information

Lecture 7: Implementing Lists, Version 2

Lecture 7: Implementing Lists, Version 2 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 7: Implementing Lists, Version 2 Contents 1 The Impact of addfirst on Lists 1 2 Mutating List Contents 2 2.1 The Basic List Classes...................................

More information

8 Hiding Implementation Details

8 Hiding Implementation Details Object-Oriented Design Lecture 8 CS 3500 Spring 2011 (Pucella) Friday, Feb 4, 2011 8 Hiding Implementation Details Last time we saw the Interpreter Design Pattern as a rather mechanical way to get an implementation

More information

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem Recursion Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem What is Recursion? A problem is decomposed into smaller sub-problems, one or more of which are simpler versions of

More information

Comp215: Structured Data Semantics

Comp215: Structured Data Semantics Comp215: Structured Data Semantics Dan S. Wallach (Rice University) Copyright! 2015, Dan S. Wallach. All rights reserved. Here s a JSON structure for a newspaper "authors": [ "name": "Alice Action", "email":

More information

Comp215: Covariance and Contravariance

Comp215: Covariance and Contravariance Comp215: Covariance and Contravariance Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. This is one of those deeper CS theory days Formal definitions aren t immediately

More information

Writing beautiful code

Writing beautiful code Writing beautiful code Dan S. Wallach and Mack Joyner, Rice University Copyright 2016 Dan Wallach, All Rights Reserved Here are two equivalent functions Map, flatmap, option static Option

More information

Comp215: More Recursion

Comp215: More Recursion Comp215: More Recursion Dan S. Wallach (Rice University) xkcd.com/1557 Copyright 2015, Dan S. Wallach. All rights reserved. Traditional, simple recursion class Fibonacci { return fib(n-1) + fib(n-2); Traditional,

More information

Structured data. Dan S. Wallach and Mack Joyner, Rice University. Copyright 2016 Dan Wallach, All Rights Reserved

Structured data. Dan S. Wallach and Mack Joyner, Rice University. Copyright 2016 Dan Wallach, All Rights Reserved Structured data Dan S. Wallach and Mack Joyner, Rice University Copyright 2016 Dan Wallach, All Rights Reserved Here s a JSON structure for a newspaper { "authors": [ { "name": "Alice Action", "email":

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Subclassing for ADTs Implementation

Subclassing for ADTs Implementation Object-Oriented Design Lecture 8 CS 3500 Fall 2009 (Pucella) Tuesday, Oct 6, 2009 Subclassing for ADTs Implementation An interesting use of subclassing is to implement some forms of ADTs more cleanly,

More information

CSCI Lab 9 Implementing and Using a Binary Search Tree (BST)

CSCI Lab 9 Implementing and Using a Binary Search Tree (BST) CSCI Lab 9 Implementing and Using a Binary Search Tree (BST) Preliminaries In this lab you will implement a binary search tree and use it in the WorkerManager program from Lab 3. Start by copying this

More information

Heaps, stacks, queues

Heaps, stacks, queues Heaps, stacks, queues Dan S. Wallach and Mack Joyner, Rice University Copyright 216 Dan Wallach, All Rights Reserved Where was Prof. Wallach on Tuesday? Two hours of scintillating Congressional testimony:

More information

Lecture 8: Iterators and More Mutation

Lecture 8: Iterators and More Mutation Integrated Introduction to Computer Science Fisler, Nelson Contents 1 Traversing Lists 1 2 Motivating Iterators 2 3 Writing an Iterator 3 4 Writing Sum with an Iterator 4 Objectives By the end of this

More information

Performance: It s harder than you d think to go fast

Performance: It s harder than you d think to go fast Performance: It s harder than you d think to go fast Dan S. Wallach and Mack Joyner, Rice University Copyright 2016 Dan Wallach, All Rights Reserved Today s lecture Prime number generation Several different

More information

6.005 Elements of Software Construction Fall 2008

6.005 Elements of Software Construction Fall 2008 MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.005 elements

More information

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

CMSC131. Exceptions and Exception Handling. When things go wrong in a program, what should happen. CMSC131 Exceptions and Exception Handling When things go "wrong" in a program, what should happen. Go forward as if nothing is wrong? Try to handle what's going wrong? Pretend nothing bad happened? Crash

More information

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course : Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order

More information

About this exam review

About this exam review Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

Software Engineering /48

Software Engineering /48 Software Engineering 1 /48 Topics 1. The Compilation Process and You 2. Polymorphism and Composition 3. Small Functions 4. Comments 2 /48 The Compilation Process and You 3 / 48 1. Intro - How do you turn

More information

Kotlin for Android Developers

Kotlin for Android Developers Kotlin for Android Developers Learn Kotlin the easy way while developing an Android App Antonio Leiva This book is for sale at http://leanpub.com/kotlin-for-android-developers This version was published

More information

The compiler is spewing error messages.

The compiler is spewing error messages. Appendix B Debugging There are a few different kinds of errors that can occur in a program, and it is useful to distinguish between them in order to track them down more quickly. Compile-time errors are

More information

Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010

Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010 Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010 11 Polymorphism The functional iterator interface we have defined last lecture is nice, but it is not very general.

More information

Comp Intermediate Programming EXAM #1 February 16, 2004 Rice University - Instructors: Cox & Nguyen

Comp Intermediate Programming EXAM #1 February 16, 2004 Rice University - Instructors: Cox & Nguyen Instructions 1. This exam is conducted under the Rice Honor Code. It is a closed-notes, closed-book exam. 2. Fill in your name on every page of the exam. 3. If you forget the name of a Java class or method,

More information

CSCI 355 Lab #2 Spring 2007

CSCI 355 Lab #2 Spring 2007 CSCI 355 Lab #2 Spring 2007 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

CSCI 355 LAB #2 Spring 2004

CSCI 355 LAB #2 Spring 2004 CSCI 355 LAB #2 Spring 2004 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 10: James Cheney University of Edinburgh October 23, 2017 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

COMP 401 Fall Recitation 7: Factories and Lists

COMP 401 Fall Recitation 7: Factories and Lists COMP 401 Fall 2017 Recitation 7: Factories and Lists Agenda High-level introduction to Factories Factory Example/Exercise Introduction to Lists List Performance Exercise Quiz 2 Recitation Source Code Please

More information

Lecture Questions. Types (binary expressions, etc). Refactoring, abstraction, better engineering. Testing. Error message generation/suppression.

Lecture Questions. Types (binary expressions, etc). Refactoring, abstraction, better engineering. Testing. Error message generation/suppression. . p.1/39 Today 1. Specific questions and discussion from lecture. 2. Types: overloading, subtypes, and coercion. 3. Testing: structure and stress. 4. Objects: when, how, and why? 5. Top-down vs. bottom-up

More information

CS/ENGRD 2110 SPRING 2018

CS/ENGRD 2110 SPRING 2018 CS/ENGRD 2110 SPRING 2018 Lecture 7: Interfaces and http://courses.cs.cornell.edu/cs2110 1 2 St Valentine s Day! It's Valentines Day, and so fine! Good wishes to you I consign.* But since you're my students,

More information

Cloning Enums. Cloning and Enums BIU OOP

Cloning Enums. Cloning and Enums BIU OOP Table of contents 1 Cloning 2 Integer representation Object representation Java Enum Cloning Objective We have an object and we need to make a copy of it. We need to choose if we want a shallow copy or

More information

void insert( Type const & ) void push_front( Type const & )

void insert( Type const & ) void push_front( Type const & ) 6.1 Binary Search Trees A binary search tree is a data structure that can be used for storing sorted data. We will begin by discussing an Abstract Sorted List or Sorted List ADT and then proceed to describe

More information

CS 61B Discussion 5: Inheritance II Fall 2014

CS 61B Discussion 5: Inheritance II Fall 2014 CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation

More information

(Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 AM, Oct 27, 2017

(Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 AM, Oct 27, 2017 Integrated Introduction to Computer Science Hughes (Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 Contents 1 Announcements 1 2 An OCaml Debugging Tip 1 3 Introduction to Rackette

More information

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

More information

Array Based Lists. Collections

Array Based Lists. Collections Array Based Lists Reading: RS Chapter 15 1 Collections Data structures stores elements in a manner that makes it easy for a client to work with the elements Specific collections are specialized for particular

More information

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the

More information

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 Contents 1 Mutation in the Doghouse 1 1.1 Aside: Access Modifiers..................................

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

17 Multiple Inheritance and ADT Extensions

17 Multiple Inheritance and ADT Extensions Object-Oriented Design Lecture 17 CS 3500 Spring 2010 (Pucella) Friday, Mar 19, 2010 17 Multiple Inheritance and ADT Extensions We looked last time at inheritance and delegation as two ways to reuse implementation

More information

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016 INTERPRETERS 8 COMPUTER SCIENCE 61A November 3, 2016 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In

More information

AP Computer Science A Summer Assignment 2017

AP Computer Science A Summer Assignment 2017 AP Computer Science A Summer Assignment 2017 The objective of this summer assignment is to ensure that each student has the ability to compile and run code on a computer system at home. We will be doing

More information

Faculty of Science FINAL EXAMINATION

Faculty of Science FINAL EXAMINATION Faculty of Science FINAL EXAMINATION COMPUTER SCIENCE COMP 250 INTRODUCTION TO COMPUTER SCIENCE Examiner: Prof. Michael Langer April 27, 2010 Associate Examiner: Mr. Joseph Vybihal 9 A.M. 12 P.M. Instructions:

More information

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d) CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

More information

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information

COMP 110/L Lecture 19. Kyle Dewey

COMP 110/L Lecture 19. Kyle Dewey COMP 110/L Lecture 19 Kyle Dewey Outline Inheritance extends super Method overriding Automatically-generated constructors Inheritance Recap -We talked about object-oriented programming being about objects

More information

hw6, BFS, debugging CSE 331 Section 5 10/25/12 Slides by Kellen Donohue

hw6, BFS, debugging CSE 331 Section 5 10/25/12 Slides by Kellen Donohue hw6, BFS, debugging CSE 331 Section 5 10/25/12 Slides by Kellen Donohue Agenda hw4 being graded hw5 may be graded first, for feedback to be used on hw6 hw6 due next week Today hw6 BFS Debugging hashcode()

More information

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) What is the Metacircular Evaluator? It is the best part

More information

Lecture 19: Signatures, Structures, and Type Abstraction

Lecture 19: Signatures, Structures, and Type Abstraction 15-150 Lecture 19: Signatures, Structures, and Type Abstraction Lecture by Dan Licata March 27, 2012 In these lectures, we will discuss the use of the ML module system for structuring large programs. Key

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

CS 4349 Lecture August 21st, 2017

CS 4349 Lecture August 21st, 2017 CS 4349 Lecture August 21st, 2017 Main topics for #lecture include #administrivia, #algorithms, #asymptotic_notation. Welcome and Administrivia Hi, I m Kyle! Welcome to CS 4349. This a class about algorithms.

More information

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides 1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of

More information

Comp Intermediate Programming EXAM #1 February 12, 2003 Rice University - Instructors: Cox & Nguyen

Comp Intermediate Programming EXAM #1 February 12, 2003 Rice University - Instructors: Cox & Nguyen Instructions 1. This exam is conducted under the Rice Honor Code. It is a closed-notes, closed-book exam. 2. Fill in your name on every page of the exam. 3. If you forget the name of a Java class or method,

More information

Recursive Data and Recursive Functions

Recursive Data and Recursive Functions Structural Recursion and Induction Of all the material in this course, this lesson is probably the hardest for students to grasp at first, but it s also one of the most fundamental. Once you understand

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2005 P. N. Hilfinger Project #2: Static Analyzer for Pyth Due: Wednesday, 6 April

More information

Comp Intermediate Programming EXAM #2 April 03, 2002 Rice University - Instructors: Cox & Nguyen

Comp Intermediate Programming EXAM #2 April 03, 2002 Rice University - Instructors: Cox & Nguyen Instructions 1. This exam is conducted under the Rice Honor Code. It is a closed-notes, closed-book exam. 2. Fill in your name on every page of the exam. 3. If you forget the name of a Java class or method,

More information

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 11 STLC Extensions and Related Topics Dan Grossman Spring 2011 Review e ::= λx. e x e e c v ::= λx. e c τ ::= int τ τ Γ ::= Γ, x : τ (λx. e) v e[v/x] e 1 e 1 e 1 e

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

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019 CS18 Integrated Introduction to Computer Science Fisler Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019 Contents 1 Overview of Generic/Parameterized Types 2 2 Double the Fun with Doubly-Linked Lists

More information

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12 CS 151 Linked Lists, Recursively Implemented 1 2 Linked Lists, Revisited Recall that a linked list is a structure that represents a sequence of elements that are stored non-contiguously in memory. We can

More information

Strings are not collections, but they behave like them in almost every way. For example,

Strings are not collections, but they behave like them in almost every way. For example, Functional Programming Style Drew McDermott drew.mcdermott@yale.edu 2015-09-30 & 10-02 Revised 2015-10-15, by addition of paragraph on type ascription in case clauses at the end of the section Variable

More information

LAMBDA EXPRESSIONS. Summer 2018

LAMBDA EXPRESSIONS. Summer 2018 LAMBDA EXPRESSIONS Summer 2018 LAMBDA EXPRESSIONS USES Introduced in Java SE 8, lambda expressions are a way to create single-method classes in your code in a much less cumbersome manner than anonymous

More information

CSE 143 Au03 Final Exam Page 1 of 15

CSE 143 Au03 Final Exam Page 1 of 15 CSE 143 Au03 Final Exam Page 1 of 15 Reference information about many standard Java classes appears at the end of the test. You might want to tear off those pages to make them easier to refer to while

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #13, Concurrency, Interference, and Synchronization John Ridgway March 12, 2015 Concurrency and Threads Computers are capable of doing more

More information

CIS 194: Homework 7. Due Wednesday, 25 March. Preliminaries. Finger exercises

CIS 194: Homework 7. Due Wednesday, 25 March. Preliminaries. Finger exercises CIS 194: Homework 7 Due Wednesday, 25 March Figure 1: The Haskell logo is modelled after the bind function (>>=) in the Monad type class Preliminaries Just as Haskell Strings are not as efficient as ByteStrings,

More information

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple movie data system. Milestones: 1. Use

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics Inf1-OOP OOP Exam Review Perdita Stevens, adapting earlier version by Ewan Klein School of Informatics March 16, 2015 Overview Overview of examinable material: Lectures Topics S&W sections Week 1 Compilation,

More information

CSE413 Midterm. Question Max Points Total 100

CSE413 Midterm. Question Max Points Total 100 CSE413 Midterm 05 November 2007 Name Student ID Answer all questions; show your work. You may use: 1. The Scheme language definition. 2. One 8.5 * 11 piece of paper with handwritten notes Other items,

More information

Lab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018

Lab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018 Contents 1 Heapsort 2 2 Quicksort 2 3 Bubble Sort 3 4 Merge Sort 3 5 Mirror Mirror

More information

CS61C : Machine Structures

CS61C : Machine Structures inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 4 C Pointers 2004-09-08 Lecturer PSOE Dan Garcia www.cs.berkeley.edu/~ddgarcia Cal flies over Air Force We re ranked 13 th in the US and

More information

Object-Oriented Design Lecture 23 CS 3500 Fall 2009 (Pucella) Tuesday, Dec 8, 2009

Object-Oriented Design Lecture 23 CS 3500 Fall 2009 (Pucella) Tuesday, Dec 8, 2009 Object-Oriented Design Lecture 23 CS 3500 Fall 2009 (Pucella) Tuesday, Dec 8, 2009 23 Odds and Ends In this lecture, I want to touch on a few topics that we did not have time to cover. 23.1 Factory Methods

More information

CS 10: Problem solving via Object Oriented Programming. Lists Part 1

CS 10: Problem solving via Object Oriented Programming. Lists Part 1 CS 10: Problem solving via Object Oriented Programming Lists Part 1 Agenda 1. Defining a List ADT 2. Generics 3. Singly linked list implementaeon 4. ExcepEons 5. Visibility: public vs. private vs. protected

More information

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Fall CS 101: Test 2 Name UVA  ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17. Grading Page 1 / 4 Page3 / 20 Page 4 / 13 Page 5 / 10 Page 6 / 26 Page 7 / 17 Page 8 / 10 Total / 100 1. (4 points) What is your course section? CS 101 CS 101E Pledged Page 1 of 8 Pledged The following

More information

CS 101 Fall 2005 Midterm 2 Name: ID:

CS 101 Fall 2005 Midterm 2 Name:  ID: This exam is open text book but closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts (in particular, the final two questions are worth substantially more than any

More information

Type Checking in COOL (II) Lecture 10

Type Checking in COOL (II) Lecture 10 Type Checking in COOL (II) Lecture 10 1 Lecture Outline Type systems and their expressiveness Type checking with SELF_TYPE in COOL Error recovery in semantic analysis 2 Expressiveness of Static Type Systems

More information

Java Review: Objects

Java Review: Objects Outline Java review Abstract Data Types (ADTs) Interfaces Class Hierarchy, Abstract Classes, Inheritance Invariants Lists ArrayList LinkedList runtime analysis Iterators Java references 1 Exam Preparation

More information

Kotlin for Android Developers

Kotlin for Android Developers Kotlin for Android Developers Learn Kotlin the easy way while developing an Android App Antonio Leiva This book is for sale at http://leanpub.com/kotlin-for-android-developers This version was published

More information

Lab 4: Imperative & Debugging 12:00 PM, Feb 14, 2018

Lab 4: Imperative & Debugging 12:00 PM, Feb 14, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lab 4: Imperative & Debugging 12:00 PM, Feb 14, 2018 Contents 1 Imperative Programming 1 1.1 Sky High Grades......................................

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 11: James Cheney University of Edinburgh November 3, 2015 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while Pull Lecture Materials and Open PollEv Poll Everywhere: pollev.com/comp110 Lecture 12 else-if and while loops Once in a while Fall 2016 if-then-else Statements General form of an if-then-else statement:

More information

Hints for Exercise 4: Recursion

Hints for Exercise 4: Recursion Hints for Exercise 4: Recursion EECS 111, Winter 2017 Due Wednesday, Jan 8th by 11:59pm Question 1: multiply-list For many list problems, this one included, the base case is when the list is empty, which

More information

Announcements. Working on requirements this week Work on design, implementation. Types. Lecture 17 CS 169. Outline. Java Types

Announcements. Working on requirements this week Work on design, implementation. Types. Lecture 17 CS 169. Outline. Java Types Announcements Types Working on requirements this week Work on design, implementation Lecture 17 CS 169 Prof. Brewer CS 169 Lecture 16 1 Prof. Brewer CS 169 Lecture 16 2 Outline Type concepts Where do types

More information

Problem 1: Building and testing your own linked indexed list

Problem 1: Building and testing your own linked indexed list CSCI 200 Lab 8 Implementing a Linked Indexed List In this lab, you will be constructing a linked indexed list. You ll then use your list to build and test a new linked queue implementation. Objectives:

More information

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures 1 Lexical Scope SML, and nearly all modern languages, follow the Rule of Lexical Scope: the body of a function is evaluated

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 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

Errors and Exceptions

Errors and Exceptions Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying

More information