Recursion in Scala. 2 Definitions A recursive method is a method that calls itself A method is indirectly recursive if it calls a method that calls a.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 Recursive Algorithms.
Advertisements

Lecture Computer Science I - Martin Hardwick Recursion rA recursive function must have at least two parts l A part that solves a simple case of the.
Chapter 7. Binary Search Trees
Lilian Blot Recursion Autumn 2012 TPOP 1. Lilian Blot Recursion Autumn 2012 TPOP 2.
For(int i = 1; i
CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
Recursion Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein.
ML Declarations.1 Standard ML Declarations. ML Declarations.2 Declarations o Re-declaration of names in ML o The reserved words "val rec" o Pattern Matching.
22C:19 Discrete Structures Induction and Recursion Spring 2014 Sukumar Ghosh.
ML Declarations.1 Standard ML Declarations. ML Declarations.2  Area of a circle: - val pi = ; val pi = : real - fun area (r) = pi*r*r;
More about functions Plus a few random things. 2 Tail recursion A function is said to be tail recursive if the recursive call is the very last thing it.
1 Divide & Conquer Algorithms. 2 Recursion Review A function that calls itself either directly or indirectly through another function Recursive solutions.
Recursion Introduction to Computing Science and Programming I.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Csci1300 Introduction to Programming Recursion Dan Feng.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Recursion. Basic problem solving technique is to divide a problem into smaller sub problems These sub problems may also be divided into smaller sub problems.
Comp 245 Data Structures Recursion. What is Recursion? A problem solving concept which can be used with languages that support the dynamic allocation.
Cosc236/recursion1 Recursion Recursive method calls itself Recursion frequently occurs in mathematics Recursive definition –2 parts base part (basis) recursive.
Return function Random function Recursion function Function in C 1.
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
Hopefully this lesson will give you an inception of what recursion is.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Functions-Recall 1. 2 Parameter passing & return void main() { int x=10, y=5; printf (“M1: x = %d, y = %d\n”, x, y); interchange (x, y); printf (“M2:
Chapter 5 – Functions II Outline Recursion Examples Using Recursion: The Fibonacci Series.
Computer Science 101 A Survey of Computer Science QuickSort.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
Compiler (scalac, gcc) Compiler (scalac, gcc) I = 0 while (i < 10) { i = i + 1 } I = 0 while (i < 10) { i = i + 1 } source code i d 3 = 0 LF w i d 3 =
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
W1-1 University of Washington Computer Programming I Recursion © 2000 UW CSE.
1 CSC103: Introduction to Computer and Programming Lecture No 16.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Merge Sort Comparison Left Half Data Movement Right Half Sorted.
Find!! # of comparison and exchange will be represented by Big-O notation!
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Recursion.
Recursion 4-Jun-18.
Introduction to Computing Science and Programming I
LinkedIntList(int n) Write a constructor for LinkedIntList that accepts an int n parameter and makes a list of the number from 0 to n new LinkedIntList(3)
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Recursion 12-Nov-18.
Trees.
Selection Sort Find the smallest value in the array. Put it in location zero. Find the second smallest value in the array and put it in location 1. Find.
Recursion 2-Dec-18.
Recursion 2-Dec-18.
Factorial Recursion Runtime Stack
Recursion 29-Dec-18.
CSC 253 Lecture 7.
  30 A 30 B 30 C 30 D 30 E 77 TOTALS ORIGINAL COUNT CURRENT COUNT
Stack Frames and Functions
Recursion Think ESCHER.
PROGRAMMING IN HASKELL
Recursion 10-Apr-19.
CSCE 314: Programming Languages Dr. Dylan Shell
Recursion 23-Apr-19.
Main() { int fact; fact = Factorial(4); } main fact.
ITEC324 Principle of CS III
Presentation transcript:

Recursion in Scala

2 Definitions A recursive method is a method that calls itself A method is indirectly recursive if it calls a method that calls a method... that calls the original method Mutually recursive methods are methods that call each other

3 Recursive functions...er, methods The mathematical definition of factorial is: We can define this in Scala as: def factorial(n: Long) = { if (n <= 1) 1 else n * factorial(n – 1); } This is a recursive function because it calls itself Recursive functions are legal in almost all languages 1, if n <= 1 n * factorial(n-1) otherwise factorial(n) is

4 Anatomy of a recursion def factorial(n: Long) = { if (n <= 1) 1 else n * factorial(n – 1) } Base case: does some work without making a recursive call Recursive case: recurs with a simpler parameter Extra work to convert the result of the recursive call into the result of this call

5 The four rules Do the base cases first Recur only with simpler cases Don't modify and use non-local variables You can modify them or use them, just not both Remember, parameters count as local variables, but if a parameter is a reference to an object, only the reference is local—not the referenced object Don't look down

6 Another simple example The following counts the number of elements in a list scala> def count(list: List[Any]): Int = { | if (list.isEmpty) 0 | else 1 + count(list.tail) | } count: (list: List[Any])Int scala> count(List("ace", "deuce", "trey")) res2: Int = 3 Note: For a recursive method, you must specify the return type

7 Parts of the simple example def count(list: List[Any]): Int = { | if (list.isEmpty) 0 | else 1 + count(list.tail) | } Base case: does some work without making a recursive call Recursive case: recurs with a simpler paramete r Extra work to convert the result of the recursive call into the result of this call

8 Infinite recursion The following is the recursive equivalent of an infinite loop: def toInfinityAndBeyond (x: Int): Int = toInfinityAndBeyond(x) This happened because we recurred with the same case! While this is obviously foolish, infinite recursions can happen by accident in more complex methods def collatz(n: Int): Int = if (n == 1) 1 else if (n % 2 == 0) collatz(n / 2) else collatz(3 * n - 1)

Why recursion? As long as we are dealing with linear data structures (sequences), there isn’t much need for recursion Although it can be very handy for lists Next semester we will be working with many recursively-defined data structures Example: A binary tree is a data structure consisting of A value An optional left binary tree, and An optional right binary tree The best way to work with recursively-defined data structures is with recursive functions 9

Binary trees scala> class BinaryTree(value: Any, left: Option[BinaryTree], right: Option[BinaryTree]) { | override def toString = s"($value $left $right)" | } defined class BinaryTree scala> val l = new BinaryTree("I'm left", None, None) l: BinaryTree = (I'm left None None) scala> val r = new BinaryTree("I'm right", None, None) r: BinaryTree = (I'm right None None) scala> val root = new BinaryTree("I'm the root!", Some(l), Some(r)) root: BinaryTree = (I'm the root! Some((I'm left None None)) Some((I'm right None None))) 10

Merging sorted lists scala> def merge(list1: List[Int], list2: List[Int]): List[Int] = { | if (list1 isEmpty) list2 | else if (list2 isEmpty) list1 | else if (list1.head merge(List(1, 4, 5, 7, 11), List(2, 3, 5, 10, 20)) res1: List[Int] = List(1, 2, 3, 4, 5, 5, 7, 10, 11, 20) 11

12 Reprise Do the base cases first Recur only with a simpler case Don't modify and use nonlocal variables Don't look down

The End 13