RECURSION. Week 6 Laboratory for Introduction to Programming and Algorithms Uwe R. Zimmer based on material by James Barker. Pre-Laboratory Checklist
|
|
- Easter Hunter
- 5 years ago
- Views:
Transcription
1 RECURSION Week 6 Laboratory for Introduction to Programming and Algorithms Uwe R. Zimmer based on material by James Barker Pre-Laboratory Checklist vvskills: You can write any conditional expression. vvknowledge: You know how conditions can be based upon pattern matching, boolean guards, or a mixture of both. vvyou have read the laboratory text below. Objectives In this lab, you will learn how to understand, design and implement recursive functions. You will make use of the submission testing and peer reviewing system frequently this week. Interlude: Recursion So far, you have learnt more about the structure of lists, and written some functions that use the first few elements of a list. The last exercise from last lab already went a bit further and evaluated a whole list of tokens without making much of a point of it. Yet this time you ll learn in more general terms to go through a list, without making any kind of assumptions about how many elements there are. A great first example is the sum function, which returns the total of all elements in a (numeric) list. Here is an alternative definition of the sum function over lists of Integers: (the ' at the end of sum' is needed to distinguish our function from the build-in function sum.) sum' :: [Integer] -> Integer sum' list = case list of [] -> 0 x: xs -> x + sum' xs Before you look at what s returned by this function, check out the patterns which this function attempts to match the input against. Those are the two most generic patterns for lists and the two of them together will match against any list. Convince yourself that this is the case. Go back to the interlude about list patterns in the previous lab, if in doubt. If you re paying attention, you will have also noticed that the sum function is defined in terms of itself. This is called a recursive definition, as it uses recursion: expressing something in terms of itself. At first glance, this probably seems confusing and unintuitive, but it turns out that recursion is an extremely powerful idea. Many formal definitions of computation rely heavily on the idea of recursion, and it is fundamental to how Haskell (and all other functional or logical programming languages) operate. Programming languages of different paradigms (like 1 ANU College of Engineering and Computer Science March 2015
2 imperative languages) will offer other forms of iteration as well, but almost all of them also offer recursion 1. Chances that you will ever use a programming language which does not support recursion are slim. So what does the above function definition actually say? Well, if the input list is empty, then the sum of that list is 0 this makes reasonable sense. If the input list is non-empty, then the sum of that list is calculated by adding the head element to the sum of the tail, i.e. the rest of the list. Although it makes sense, it s instructive to repeatedly expand an expression involving sum to see what happens: sum [1, 2, 3] sum [1, 2, 3] = 1 + sum [2, 3] sum [1, 2, 3] = 1 + sum [2, 3] = sum [3] sum [1, 2, 3] = 1 + sum [2, 3] = sum [3] = sum [] sum [1, 2, 3] = 1 + sum [2, 3] = sum [3] = sum [1, 2, 3] = 1 + sum [2, 3] = sum [1, 2, 3] = sum [1, 2, 3] = 6 You notice that the problem is transformed into a simpler expression which is only evaluated after we found the simple case (or base case) (in red) which we can solve without recursing. Here is another way of doing it which does the calculations while progressing through the list (as we did in lectures already, I also replaced Integer with a placeholder a which represents all numerical types just by adding the constraint (Num a) => more on this in the next lab, yet for this lab you can just read a as type standing in for any numerical type ): sum :: (Num a) => [a] -> a sum list = case list of [] -> 0 [x] -> x x: y: zs -> sum ((x + y): zs) This would expand into the following sequence of expressions: sum [1, 2, 3] sum [1, 2, 3] = sum [3, 3] sum [1, 2, 3] = sum [3, 3] = sum [6] sum [1, 2, 3] = sum [3, 3] = 6 sum [1, 2, 3] = 6 As the function calculated intermediate results while going through the list, we already have the final result when we reach the end of the list. Certainly looks shorter, but did it actually make it faster? Type: :set +s in your GHCi environment to enable statistical displays with every evaluation. Now try to run sum [(1::Integer) ] as well as sum [(1::Integer) ]. Do it a few times to see how reliable your measurements are. What does that mean? Sometimes it is not possible to use one of the existing parameters to accumulate a result, and thus a function with an additional parameter is introduced as an internal helper function. This might then look like this: 1 The programming languages which do not support recursion are either early versions of some mainstream languages (like Cobol in its original form from the 60s) or contemporary, specialized languages for high integrity systems, which might limit or forbid recursion (as they also forbid while-loops and other unbound primitives). 2 ANU College of Engineering and Computer Science March 2015
3 sum :: (Num a) => [a] -> a sum list = sum_with_extra_parameter 0 list where sum_with_extra_parameter accumulator shrinking_list = case shrinking_list of [] -> accumulator x: xs -> sum_with_extra_parameter (accumulator + x) xs This would expand into the following sequence of expressions (sum_with_extra_parameter replaced with swep): sum [1, 2, 3] = swep 0 [1, 2, 3] = swep 0 [1, 2, 3] = swep 1 [2, 3] = swep 0 [1, 2, 3] = swep 1 [2, 3] = swep 3 [3] = swep 0 [1, 2, 3] = swep 1 [2, 3] = swep 3 [3] = swep 6 [] = swep 0 [1, 2, 3] = swep 1 [2, 3] = swep 3 [3] = 6 = swep 0 [1, 2, 3] = swep 1 [2, 3] = 6 = swep 0 [1, 2, 3] = 6 = 6 Did this last version improve or degrade performance? Run sum [(1::Integer) ]. Any better? Any worse? Note that recursive functions do not have to involve lists at all. The canonical example of a simple recursive function is the factorial, i.e. n % k = 1 6n! N0: n! = k = n$ ( n-1) $ ( n-2) $ f$ 2$ 1 You can express factorials recursively: 1 ; n = 0 6 n! N 0 : n! = ) n $ ( n-1)! ; n > 0 Which translates almost one-to-one into a recursive factorial function in Haskell: import Integer_Subtypes factorial :: Natural -> Natural factorial n = case n of 0 -> 1 _ -> n * factorial (n - 1) Always nice of course to see a beautifully working solution, but even more interesting is to understand what traps I just jumped over without telling you. So let s look into what I might have gotten wrong here: Why do I include the case where n = 0? Simple: it tells the function where to stop recursing. For example, imagine that I d defined forgot_base_case :: Natural -> Natural forgot_base_case n = n * forgot_base_case (n - 1) Let s try a sample evaluation out: forgot_base_case 3 = 3 * forgot_base_case (3-1) = 3 * (2 * forgot_base_case (2-1)) = 3 * (2 * (1 * forgot_base_case (1-1))) = 3 * (2 * (1 * (0 * forgot_base_case (0-1)))) *** Exception: 0-1: Out of range for Natural 3 ANU College of Engineering and Computer Science March 2015
4 This expansion will never end, and the computer will never be able to provide an answer. This is called a non-terminating program one of the possibilities when your computer freezes up on you, while flooring the processors at the same time. However, including the case for n = 0 provides a point at which expansion ends, and the result can be computed: factorial 3 = 3 * factorial (3-1) = 3 * (2 * factorial (2-1)) = 3 * (2 * (1 * factorial (1-1))) = 3 * (2 * (1 * factorial 0)) = 3 * (2 * (1 * 1)) = 6 This case, n = 0, is called a base case. Now we have a terminating program, which is usually what we want but not always.. try to think of programs which are not supposed to terminate. The other case is called a step case. (If you studied proof by mathematical induction in high school, these terms should be familiar to you. This is not at all accidental: recursion and induction are two sides of the same coin, and complement each other perfectly.) Yet, the step case can drop the ball as well let s have a look: stepping_on_the_spot :: Natural -> Natural stepping_on_the_spot n = case n of 0 -> 1 _ -> n * stepping_on_the_spot n What happens here? stepping_on_the_spot 3 = 3 * stepping_on_the_spot 3 = 3 * (3 * stepping_on_the_spot 3) = 3 * (3 * (3 * stepping_on_the_spot 3)) =... Again we end with a non-terminating program. What else can go bad? Have a look at this function: stepping_in_the_wrong_direction :: Natural -> Natural stepping_in_the_wrong_direction n = case n of 0 -> 1 _ -> n * stepping_in_the_wrong_direction (n + 1) I leave it to you to figure out what happens here. Yet those three traps are the most common mistakes with recursive functions (or with any form of iteration really). Usually those traps are not quite as obvious as they are here, yet knowing those problem cases intimately will help you avoiding them from the beginning. Relating back to the sum example: Could we also calculate the factorial value while we recurse rather then while we return from the base case? Have a look at this version, where we accumulate the final answer in an extra parameter: factorial :: Natural -> Natural factorial n = factorial_in_parameter n 1 where factorial_in_parameter :: Natural -> Natural -> Natural factorial_in_parameter x fac = case x of 0 -> fac _ -> factorial_in_parameter (x - 1) (x * fac) 4 ANU College of Engineering and Computer Science March 2015
5 Is this version expected to also differ in performance similar to what you measured for the different sum implementations? Give it a try! When the final answer is already at hand when the base case is selected (meaning the base case already returns the final answer), then such a recursive function is called tail-recursive. Many compilers apply optimization if they detect this pattern (basically delete all the code and memory which would be otherwise needed to hand the result back through all the recursive stages which got us there), yet the practical effect will differ depending on a number of other factors (which we need to address later). Your Haskell compiler optimises in multiple other ways which may outperform tail-recursive structures. To be of any use at all, every recursive function must include a base case otherwise, its expansion will never terminate and a step case which takes it one step closer to the base case with every function call. Return to the sum' function above. Here, the base case is the case when the input is an empty list. The sole step case is the case where the input is a non-empty list. Recursive functions are a universal concept which you will find everywhere, once you recognize them as recursive. Try the following function and predict the result before you actually run it with happy_creatures Man: data Creatures = Salmon Puffin Fox Bear Man deriving (Eq, Enum, Show) happy_creatures :: Creatures -> String happy_creatures creature = case creature of Salmon -> the ++ (show creature) ++ who is always happy _ -> the ++ (show creature) ++ who dreams of eating ++ happy_creatures (pred creature) ++ which makes the ++ (show creature) ++ happy We have only scratched the surface of what can be done with recursive functions. In labs and assignments to come, you will learn to make increasingly complex uses of this technique. Exercise 1: List Product Write a function product :: (Num a) => [a] -> a, which multiplies all elements inside a list such that for instance: product [(1 :: Integer), 2, 3] = 6 product [(3 :: Integer)] = 3 product [] = 1 Submit your solution under Lab 6 List Product on the SubmissionApp ( SubmissionApp) and don t forget to have this apostrophe at the end of your function. Exercise 2: Lift them up Write a function convert_to_upper_case :: String -> String. This function should take an input of type String, and return the same String with every character converted to upper-case. The technique you use to do this will be similar, but not identical, to that used for sum. Hint: you will need to use both the attach operator : and the toupper function in the Data.Char module. You can, of course, load this module using the familiar import syntax. Submit your solution under Lab 6 Upper Cases on the SubmissionApp ( SubmissionApp) to see whether all checks out. 5 ANU College of Engineering and Computer Science March 2015
6 Exercise 3: 3 esicrexe Write a function invert which accepts any list and returns a list with the same elements, yet in reverse order. So your function should respond like this: invert [(1 :: Integer).. 10] = [10,9,8,7,6,5,4,3,2,1] invert abc = cba Reminder: you can concatenate too lists with the ++ operation. This might come in handy when you implement this function in a short way. Make sure your first shot works for the above examples and submit your solution under Lab 6 Invert on the SubmissionApp ( to see whether all checks out. Exercise 4: Fast version Now also test your function invert for: last (invert [(1 :: Integer) ]) (last being a predefined function to pick out the last element of a list.) If you find yourself hoping the it will get the job done before the lab finishes, then you need to improve your function in this exercise (this should not take longer than 0.1 seconds) otherwise you get a freebie and can submit the same function again and its own fast version under Lab 6 Invert (fast) on the SubmissionApp ( Exercise 5: Pack the rucksack Write a function which accepts a list of natural numbers and a target sum: rucksack :: [Natural] -> Natural -> [[Natural]] such that all subsequences of the original list which add up to the target sum are returned. For instance (sorted by large subsequence start numbers first): rucksack [3,7,5,9,13,17] 30 = [[13,17],[3,5,9,13]] This is a simplified version of the well known knapsack problem. Submit under Lab 6 Rucksack on the SubmissionApp ( (and also include import Integer_Subtypes at the beginning of your submission). Make Sure You Logout to Terminate Your Session! Outlook Next week you will write functions which will work for multiple types (polymorphic functions). 6 ANU College of Engineering and Computer Science March 2015
TREES. Week 8 Laboratory for Introduction to Programming and Algorithms Uwe R. Zimmer based on material by James Barker. Pre-Laboratory Checklist
TREES Week 8 Laboratory for Introduction to Programming and Algorithms Uwe R. Zimmer based on material by James Barker Pre-Laboratory Checklist vvskills: You can understand and write conditional, recursive
More informationSYNCHRONIZED DATA. Week 9 Laboratory for Concurrent and Distributed Systems Uwe R. Zimmer. Pre-Laboratory Checklist
SYNCHRONIZED DATA Week 9 Laboratory for Concurrent and Distributed Systems Uwe R. Zimmer Pre-Laboratory Checklist vvyou have read this text before you come to your lab session. vvyou understand and can
More informationIntro. 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 informationn! = 1 * 2 * 3 * 4 * * (n-1) * n
The Beauty and Joy of Computing 1 Lab Exercise 9: Problem self-similarity and recursion Objectives By completing this lab exercise, you should learn to Recognize simple self-similar problems which are
More informationDISTRIBUTION. Week 11 Laboratory for Systems, Networks and Concurrency Uwe R. Zimmer. Pre-Laboratory Checklist
DISTRIBUTION Week 11 Laboratory for Systems, Networks and Concurrency Uwe R. Zimmer Pre-Laboratory Checklist vvyou have read this text before you come to your lab session. vvyou understand and can utilize
More informationWeek 5 Tutorial Structural Induction
Department of Computer Science, Australian National University COMP2600 / COMP6260 Formal Methods in Software Engineering Semester 2, 2016 Week 5 Tutorial Structural Induction You should hand in attempts
More information(Refer Slide Time 3:31)
Digital Circuits and Systems Prof. S. Srinivasan Department of Electrical Engineering Indian Institute of Technology Madras Lecture - 5 Logic Simplification In the last lecture we talked about logic functions
More informationCIS 194: Homework 6. Due Monday, February 25. Fibonacci numbers
CIS 194: Homework 6 Due Monday, February 25 Files you should submit: Fibonacci.hs This week we learned about Haskell s lazy evaluation. This homework assignment will focus on one particular consequence
More informationFRACTALS. Week 13 Laboratory for Introduction to Programming and Algorithms Uwe R. Zimmer based on a lab by James Barker. Pre-Laboratory Checklist
FRACTALS Week 13 Laboratory for Introduction to Programming and Algorithms Uwe R. Zimmer based on a lab by James Barker Pre-Laboratory Checklist vvskills: You can handle any recursive, or higher order
More informationLecture 6: Sequential Sorting
15-150 Lecture 6: Sequential Sorting Lecture by Dan Licata February 2, 2012 Today s lecture is about sorting. Along the way, we ll learn about divide and conquer algorithms, the tree method, and complete
More informationAdmin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return
Recursion CS 1 Admin How's the project coming? After these slides, read chapter 13 in your book Yes that is out of order, but we can read it stand alone Quizzes will return Tuesday Nov 29 th see calendar
More informationThe 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 informationFunctional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda
Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered
More informationFunctional abstraction
Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered
More information6.001 Notes: Section 8.1
6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything
More information6.001 Notes: Section 4.1
6.001 Notes: Section 4.1 Slide 4.1.1 In this lecture, we are going to take a careful look at the kinds of procedures we can build. We will first go back to look very carefully at the substitution model,
More informationChapter 1. Math review. 1.1 Some sets
Chapter 1 Math review This book assumes that you understood precalculus when you took it. So you used to know how to do things like factoring polynomials, solving high school geometry problems, using trigonometric
More informationCS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist
CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist In Handout 28, the Guide to Inductive Proofs, we outlined a number of specifc issues and concepts to be mindful about when
More informationCS 360: Programming Languages Lecture 12: More Haskell
CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due
More informationInf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics
Inf1-OP Inf1-OP Exam Review Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 20, 2017 Overview Overview of examinable material: Lectures Week 1
More informationFunctional Programming in Haskell for A level teachers
Functional Programming in Haskell for A level teachers About this document Functional Programming is now part of the A level curriculum. This document is intended to get those who already have some programming
More informationPROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions
PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product
More information1 Leaffix Scan, Rootfix Scan, Tree Size, and Depth
Lecture 17 Graph Contraction I: Tree Contraction Parallel and Sequential Data Structures and Algorithms, 15-210 (Spring 2012) Lectured by Kanat Tangwongsan March 20, 2012 In this lecture, we will explore
More information6.001 Notes: Section 15.1
6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define
More informationCOMP 161 Lecture Notes 16 Analyzing Search and Sort
COMP 161 Lecture Notes 16 Analyzing Search and Sort In these notes we analyze search and sort. Counting Operations When we analyze the complexity of procedures we re determine the order of the number of
More informationProofwriting Checklist
CS103 Winter 2019 Proofwriting Checklist Cynthia Lee Keith Schwarz Over the years, we ve found many common proofwriting errors that can easily be spotted once you know how to look for them. In this handout,
More informationIMPLICIT CONCURRENCY
IMPLICIT CONCURRENCY Week 8 Laboratory for Concurrent and Distributed Systems Uwe R. Zimmer Pre-Laboratory Checklist vvyou have read this text before you come to your lab session. vvyou understand and
More informationProgramming Languages 3. Definition and Proof by Induction
Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.
More informationLists. Michael P. Fourman. February 2, 2010
Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce
More informationLecture 8: Summary of Haskell course + Type Level Programming
Lecture 8: Summary of Haskell course + Type Level Programming Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 31, 2017 Principles from Haskell
More informationAlgorithm Design and Recursion. Search and Sort Algorithms
Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms
More informationI2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub I2204- Imperative Programming Schedule 08h00-09h40
More informationAn Interesting Way to Combine Numbers
An Interesting Way to Combine Numbers Joshua Zucker and Tom Davis October 12, 2016 Abstract This exercise can be used for middle school students and older. The original problem seems almost impossibly
More informationComputer Science 210 Data Structures Siena College Fall Topic Notes: Recursive Methods
Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Recursive Methods You have seen in this course and in your previous work that iteration is a fundamental building block that we
More informationBasics of Computational Geometry
Basics of Computational Geometry Nadeem Mohsin October 12, 2013 1 Contents This handout covers the basic concepts of computational geometry. Rather than exhaustively covering all the algorithms, it deals
More informationLaboratory 5: Implementing Loops and Loop Control Strategies
Laboratory 5: Implementing Loops and Loop Control Strategies Overview: Objectives: C++ has three control structures that are designed exclusively for iteration: the while, for and do statements. In today's
More informationNumber Systems Using and Converting Between Decimal, Binary, Octal and Hexadecimal Number Systems
Number Systems Using and Converting Between Decimal, Binary, Octal and Hexadecimal Number Systems In everyday life, we humans most often count using decimal or base-10 numbers. In computer science, it
More informationDISTRIBUTING SERVER. Week 8 Laboratory for Concurrent and Distributed Systems Uwe R. Zimmer based on material by Alistair Rendell
DISTRIBUTING SERVER Week 8 Labaty f Concurrent and Distributed Systems Uwe R. Zimmer based on material by Alistair Rendell Pre-Labaty Checklist vvyou have read this text befe you come to your lab session.
More informationCS103 Spring 2018 Mathematical Vocabulary
CS103 Spring 2018 Mathematical Vocabulary You keep using that word. I do not think it means what you think it means. - Inigo Montoya, from The Princess Bride Consider the humble while loop in most programming
More informationIteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration?
Iteration Part 1 Motivation for iteration Display time until no more time left Iteration is a problemsolving strategy found in many situations. Keep coding until all test cases passed CS111 Computer Programming
More informationCourse year Typeclasses and their instances
Course year 2016-2017 Typeclasses and their instances Doaitse Swierstra and Atze Dijkstra with extra s Utrecht University September 29, 2016 1. The basics 2 Overloading versus parametric polymorphism 1
More information3. Simple Types, Variables, and Constants
3. Simple Types, Variables, and Constants This section of the lectures will look at simple containers in which you can storing single values in the programming language C++. You might find it interesting
More informationLab 7: OCaml 12:00 PM, Oct 22, 2017
CS17 Integrated Introduction to Computer Science Hughes Lab 7: OCaml 12:00 PM, Oct 22, 2017 Contents 1 Getting Started in OCaml 1 2 Pervasives Library 2 3 OCaml Basics 3 3.1 OCaml Types........................................
More informationProject 5 - The Meta-Circular Evaluator
MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 2005 Project 5 - The Meta-Circular
More informationRecursion. Recursion [Bono] 1
Recursion Idea A few examples wishful thinking method Recursion in classes Ex: palindromes Helper functions Computational complexity of recursive functions Recursive functions with multiple calls Recursion
More informationTypes, Expressions, and States
8/27: solved Types, Expressions, and States CS 536: Science of Programming, Fall 2018 A. Why? Expressions represent values in programming languages, relative to a state. Types describe common properties
More informationprintf( Please enter another number: ); scanf( %d, &num2);
CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful
More informationMeeting13:Denotations
Meeting13:Denotations Announcements Homework 3 due next week Friday at 6:00pm Homework2Comments Time: 29.2 hours avg Difficulty: 5.4 avg Issues Length? (Part 2 out Wed instead of Mon) Misunderstanding
More informationThis example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator
1 2 This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator (total) and a counter (i); it works by assigning
More informationstructure syntax different levels of abstraction
This and the next lectures are about Verilog HDL, which, together with another language VHDL, are the most popular hardware languages used in industry. Verilog is only a tool; this course is about digital
More informationHere is a list of lecture objectives. They are provided for you to reflect on what you are supposed to learn, rather than an introduction to this
This and the next lectures are about Verilog HDL, which, together with another language VHDL, are the most popular hardware languages used in industry. Verilog is only a tool; this course is about digital
More informationProgramming and Data Structure
Programming and Data Structure Dr. P.P.Chakraborty Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture # 09 Problem Decomposition by Recursion - II We will
More informationAlgebraic Specifications
Object-Oriented Design Lecture 2 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 11, 2007 Algebraic Specifications Last time I said a word about the abstraction barrier, separating the clients from the implementors.
More information#23: Sequences March 28, 2009
#23: Sequences March 28, 2009 a mysterious rule easy peasy Suppose n is an integer, and consider this simple rule: if n is even, divide it by two; otherwise, multiply n by 3, and add one. Pretty simple,
More informationIntroduction to Algorithms / Algorithms I Lecturer: Michael Dinitz Topic: Shortest Paths Date: 10/13/15
600.363 Introduction to Algorithms / 600.463 Algorithms I Lecturer: Michael Dinitz Topic: Shortest Paths Date: 10/13/15 14.1 Introduction Today we re going to talk about algorithms for computing shortest
More informationModule 8: Local and functional abstraction
Module 8: Local and functional abstraction Readings: HtDP, Intermezzo 3 (Section 18); Sections 19-23. We will cover material on functional abstraction in a somewhat different order than the text. We will
More informationExcel Basics: Working with Spreadsheets
Excel Basics: Working with Spreadsheets E 890 / 1 Unravel the Mysteries of Cells, Rows, Ranges, Formulas and More Spreadsheets are all about numbers: they help us keep track of figures and make calculations.
More informationRepetition Through Recursion
Fundamentals of Computer Science I (CS151.02 2007S) Repetition Through Recursion Summary: In many algorithms, you want to do things again and again and again. For example, you might want to do something
More informationDiscussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:
Discussion 2C Notes (Week 5, February 4) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Recursion A recursion is a function-writing technique where the function
More informationThis course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.
This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units. Introduction Overview Advancements in technology are
More informationHow invariants help writing loops Author: Sander Kooijmans Document version: 1.0
How invariants help writing loops Author: Sander Kooijmans Document version: 1.0 Why this document? Did you ever feel frustrated because of a nasty bug in your code? Did you spend hours looking at the
More informationCOP4020 Programming Assignment 1 - Spring 2011
COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to
More informationSolution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors
Solution sheet 1 Introduction Please note that there can be other solutions than those listed in this document. This is a literate Haskell file which is available as PDF, as well as literate Haskell source
More informationROUNDING ERRORS LAB 1. OBJECTIVE 2. INTRODUCTION
ROUNDING ERRORS LAB Imagine you are traveling in Italy, and you are trying to convert $27.00 into Euros. You go to the bank teller, who gives you 20.19. Your friend is with you, and she is converting $2,700.00.
More informationp x i 1 i n x, y, z = 2 x 3 y 5 z
3 Pairing and encoding functions Our aim in this part of the course is to show that register machines can compute everything that can be computed, and to show that there are things that can t be computed.
More informationSummer 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 informationStacks and queues (chapters 6.6, 15.1, 15.5)
Stacks and queues (chapters 6.6, 15.1, 15.5) So far... Complexity analysis For recursive and iterative programs Sorting algorithms Insertion, selection, quick, merge, (intro, dual-pivot quick, natural
More informationDivisibility Rules and Their Explanations
Divisibility Rules and Their Explanations Increase Your Number Sense These divisibility rules apply to determining the divisibility of a positive integer (1, 2, 3, ) by another positive integer or 0 (although
More informationMITOCW watch?v=0jljzrnhwoi
MITOCW watch?v=0jljzrnhwoi The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To
More informationScan and its Uses. 1 Scan. 1.1 Contraction CSE341T/CSE549T 09/17/2014. Lecture 8
CSE341T/CSE549T 09/17/2014 Lecture 8 Scan and its Uses 1 Scan Today, we start by learning a very useful primitive. First, lets start by thinking about what other primitives we have learned so far? The
More informationTreaps. 1 Binary Search Trees (BSTs) CSE341T/CSE549T 11/05/2014. Lecture 19
CSE34T/CSE549T /05/04 Lecture 9 Treaps Binary Search Trees (BSTs) Search trees are tree-based data structures that can be used to store and search for items that satisfy a total order. There are many types
More informationCSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch
CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch Purpose: We will take a look at programming this week using a language called Scratch. Scratch is a programming language that was developed
More informationExercises: Instructions and Advice
Instructions Exercises: Instructions and Advice The exercises in this course are primarily practical programming tasks that are designed to help the student master the intellectual content of the subjects
More informationWhat is Iteration? CMPT-101. Recursion. Understanding Recursion. The Function Header and Documentation. Recursively Adding Numbers
What is Iteration? CMPT-101 Week 6 Iteration, Iteration, Iteration, Iteration, Iteration, Iteration,... To iterate means to do the same thing again and again and again and again... There are two primary
More informationFunctional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute
Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute Module # 02 Lecture - 03 Characters and Strings So, let us turn our attention to a data type we have
More informationRACKET BASICS, ORDER OF EVALUATION, RECURSION 1
RACKET BASICS, ORDER OF EVALUATION, RECURSION 1 COMPUTER SCIENCE 61AS 1. What is functional programming? Give an example of a function below: Functional Programming In functional programming, you do not
More informationCOMMUNICATING TASKS. Week 6 Laboratory for Concurrent and Distributed Systems Uwe R. Zimmer based on material by Alistair Rendell
COMMUNICATING TASKS Week 6 Laboratory for Concurrent and Distributed Systems Uwe R. Zimmer based on material by Alistair Rendell Pre-Laboratory Checklist vvyou have read this text before you come to your
More informationEECS 140 Laboratory Exercise 5 Prime Number Recognition
1. Objectives EECS 140 Laboratory Exercise 5 Prime Number Recognition A. Become familiar with a design process B. Practice designing, building, and testing a simple combinational circuit 2. Discussion
More informationAnjuli Kannan. Google Earth Driving Simulators (3:00-7:00)
Google Earth Driving Simulators (3:00-7:00) An example of what you can do by learning the GoogleEarth API, once you know how to write code Google has published such an API so that people can make programs
More informationHints 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 informationRECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012
RECURSION 7 COMPUTER SCIENCE 61A October 15, 2012 1 Recursion We say a procedure is recursive if it calls itself in its body. Below is an example of a recursive procedure to find the factorial of a positive
More information9 abcd = dcba b + 90c = c + 10b b = 10c.
In this session, we ll learn how to solve problems related to place value. This is one of the fundamental concepts in arithmetic, something every elementary and middle school mathematics teacher should
More informationScan and Quicksort. 1 Scan. 1.1 Contraction CSE341T 09/20/2017. Lecture 7
CSE341T 09/20/2017 Lecture 7 Scan and Quicksort 1 Scan Scan is a very useful primitive for parallel programming. We will use it all the time in this class. First, lets start by thinking about what other
More informationLecture 2: SML Basics
15-150 Lecture 2: SML Basics Lecture by Dan Licata January 19, 2012 I d like to start off by talking about someone named Alfred North Whitehead. With someone named Bertrand Russell, Whitehead wrote Principia
More informationTesting and Debugging
130 Chapter 5 Testing and Debugging You ve written it so it must work, right? By now you know that is not necessarily true. We all make mistakes. To be a successful programmer you need to be able to reliably
More informationCS 051 Homework Laboratory #2
CS 051 Homework Laboratory #2 Dirty Laundry Objective: To gain experience using conditionals. The Scenario. One thing many students have to figure out for the first time when they come to college is how
More information(Refer Slide Time: 00:51)
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute Technology, Madras Module 10 E Lecture 24 Content Example: factorial
More information9 abcd = dcba b + 90c = c + 10b b = 10c.
In this session, we ll learn how to solve problems related to place value. This is one of the fundamental concepts in arithmetic, something every elementary and middle school mathematics teacher should
More informationAnimator Friendly Rigging Part 1
Animator Friendly Rigging Part 1 Creating animation rigs which solve problems, are fun to use, and don t cause nervous breakdowns. - http://jasonschleifer.com/ - 1- CONTENTS I. INTRODUCTION... 4 What is
More informationTuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example
CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,
More informationCS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class
CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount
More informationDrawing Hands, by M. C. Escher (lithograph, 1948)
Drawing Hands, by M. C. Escher (lithograph, 1948) 12 The Leap of Faith In the combining method, we build up to a recursive procedure by writing a number of special-case nonrecursive procedures, starting
More informationThe Haskell HOP: Higher-order Programming
The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments
More informationLecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning
Lecture 1 Contracts 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,
More informationHomework: More Abstraction, Trees, and Lists
Homework: More Abstraction, Trees, and Lists COMP 50 Fall 2013 This homework is due at 11:59PM on Monday, November 18. Submit your solutions in a single file using the COMP 50 Handin button on DrRacket;
More informationFoundations, Reasoning About Algorithms, and Design By Contract CMPSC 122
Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122 I. Logic 101 In logic, a statement or proposition is a sentence that can either be true or false. A predicate is a sentence in
More informationCMPSCI 187 / Spring 2015 Postfix Expression Evaluator
CMPSCI 187 / Spring 2015 Postfix Expression Evaluator Due on Thursday, 05 March, 8:30 a.m. Marc Liberatore and John Ridgway Morrill I N375 Section 01 @ 10:00 Section 02 @ 08:30 1 CMPSCI 187 / Spring 2015
More informationThe Art of Recursion: Problem Set 10
The Art of Recursion: Problem Set Due Tuesday, November Tail recursion A recursive function is tail recursive if every recursive call is in tail position that is, the result of the recursive call is immediately
More informationInf1-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 informationWeek 2: Git and First Functions
Week 2: Git and First Functions Steven X. Han 2017-07-31 In this lab you will complete Lab 1 by submitting your work into git so that your tutor can access it. To do so successfully, read all explanations
More information