Recursion & Iteration

Similar documents
Functions, Conditionals & Predicates

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Review of Functional Programming

Lecture Notes on Lisp A Brief Introduction

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE,

Common Lisp. Blake McBride

Functional programming with Common Lisp

Common LISP-Introduction

Debugging in LISP. trace causes a trace to be printed for a function when it is called

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Department of Computer and information Science Norwegian University of Science and Technology

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

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

INF4820. Common Lisp: Closures and Macros

Lisp. Versions of LISP

Common LISP Tutorial 1 (Basic)

Chapter 1. Fundamentals of Higher Order Programming

Lisp Basic Example Test Questions

Documentation for LISP in BASIC

1.3. Conditional expressions To express case distinctions like

CS 480. Lisp J. Kosecka George Mason University. Lisp Slides

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

Putting the fun in functional programming

Functional Programming. Pure Functional Programming

(defun fill-nodes (nodes texts name) (mapcar #'fill-node (replicate-nodes nodes (length texts) name) texts))

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

19 Machine Learning in Lisp

Midterm Examination (Sample Solutions), Cmput 325

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

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

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY,

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Symbolic Computation and Common Lisp

CS 314 Principles of Programming Languages

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

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

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

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

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

An Explicit-Continuation Metacircular Evaluator

Imperative, OO and Functional Languages A C program is

User-defined Functions. Conditional Expressions in Scheme

Functional Programming Languages (FPL)

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

;; definition of function, fun, that adds 7 to the input (define fun (lambda (x) (+ x 7)))

Homework #2. Source code with description. Tzewen Wang ECE578 Winter 2005

CSC 533: Programming Languages. Spring 2015

Functional Programming - 2. Higher Order Functions

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination

MIDTERM EXAMINATION - CS130 - Spring 2005

A Brief Introduction to Scheme (II)

Pattern Matching WIlensky Chapter 21

CS 314 Principles of Programming Languages. Lecture 16

LECTURE 16. Functional Programming

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

Tail Recursion and Accumulators

CS 314 Principles of Programming Languages

Allegro CL Certification Program

Building a system for symbolic differentiation

Homework 1. Reading. Problems. Handout 3 CSCI 334: Spring, 2012

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

A brief tour of history

Fundamentals of Programming Session 13

Heap storage. Dynamic allocation and stacks are generally incompatible.

CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires

Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

ALISP interpreter in Awk

An introduction to Scheme

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CS61A Midterm 2 Review (v1.1)

Imperative languages

Project 2: Scheme Interpreter

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

Functions and Recursion. Dr. Philip Cannata 1

CSc 520. Principles of Programming Languages 7: Scheme List Processing

Functional Programming. Big Picture. Design of Programming Languages

Homework. Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25

YOUR NAME PLEASE: *** SOLUTIONS ***

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

Introduction to lambda calculus Part 3

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CSc 520 Principles of Programming Languages. Examining Lists. Constructing Lists... 7: Scheme List Processing

Functional Programming. Functional Programming

Functional Programming. Pure Functional Languages

A little bit of Lisp

15 Unification and Embedded Languages in Lisp

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

Associative Database Managment WIlensky Chapter 22

Transcription:

Recursion & Iteration York University Department of Computer Science and Engineering 1

Overview Recursion Examples Iteration Examples Iteration vs. Recursion Example [ref.: Chap 5,6 Wilensky] 2

Recursion A natural programming style in LISP A function is recursive if it calls itself Boundary condition: stopping recursion Recursive condition: must be a smaller problem to converge 3

Example factorial (defun factorial (n) (cond ((zerop n) 1) (t (* n (factorial (1 n)))) )) The above code works if n is a positive integer. Other numbers (not positive integers) will not reach the boundary condition and a stack overflow error will be encountered. A better implementation: (defun factorial (n) (cond ((not (and (integerp n) (>= n 0))) nil) ((zerop n) 1) (t (* n (factorial (1 n)))) )) 4

Example length of list Using cond: (defun llist (lst) (cond ((null lst) 0) (t (1+ (llist (cdr lst)))) )) Using if: (defun llist (lst) (if (null lst) 0 (1+ (llist (cdr lst))) )) This one will return 0 if an empty list or an atom (note nil is an atom) (defun llist (lst) (if (atom lst) 0 (1+ (llist (cdr lst))) )) 5

Example member of list Test if an element is a member of a list (defun lmember (e lst) (cond ((null lst) nil) ((equal e (car lst)) ) (t (lmember e (cdr lst))) )) Another way of writing above is: (defun lmember (e lst) (and lst (or The second argument of or will be evaluated, only if the first is evaluated to false (equal e (car lst)) (lmember e (cdr lst)) ))) The second argument of and will be evaluated, only if the first is evaluated to true (i.e. non nil) 6

Example member of list Test if an element is a member of a list, return the portion of list from the point of first match (defun lmember (e lst) (cond ((null lst) nil) ((equal e (car lst)) lst) (t (lmember e (cdr lst))) )) Exercise: Write a function that looks for members inside nested lists. 7

Example substitution in nested lists Function lsubst(in out lst) substitutes every occurrence of out with in in lst, which can be a list or an atom. e.g. (lsubst a x (b (x x) x)) will evaluate to (B (A A) A) (defun lsubst (in out lst) (cond ((equal out lst) in) ; if lst is out, return in ((atom lst) lst) ; otherwise if atom, no change ; otherwise two recursions cons ed (t (cons (lsubst in out (car lst)) (lsubst in out (cdr lst)) )) )) Exercise: Change the function definition to only substitute if lst is a list (no change if it is an atom) 8

Iteration Iteration: A loop, to be executed repeatedly Boundary condition (or terminating condition) A return value upon termination Index variables, their initial value, and the modification rule upon each iteration Unlike recursion, we need special functions, such as do to implement iteration 9

Iteration Do General form (do ((var1 val1 rep1) (var2 val2 rep2)...) exit clause form1 form2...) In which exit clause can be nil or in the form of (test test form1 test form2...) 1. Assign all vari with corresponding (evaluated) vali in parallel. 2. Examine exit clause. If nil, return nil as value of do (and stop). Otherwise, if test evaluates to true, evaluate test formi in order. Return the value of the last form as the value of do (and stop). 3. If test evaluates to false, evaluate formi in order. 4. Assign all vari with corresponding (evaluated) repi in parallel. 5. Go to step 2. 10

Example Find length of list For example : > (dolength (x y z)) 3 (defun dolength(lst) (do ( (tlst lst (cdr tlst)) (sum 0 (1+ sum))) ( (atom tlst) sum ) )) Two index variables: tlst and sum They are just like formal parameters: local to do. Terminating condition: when the list is an atom (including nil) Value of sum is returned upon termination. 11

Examples Use do to return a list which is the same as a list lst1 without the first n elements assuming its length is greater than n (do ((x n (1 x)) (lst2 lst1 (cdr lst2))) ( (zerop x) lst2)) Use do to return a list of numbers from 1 to n (do ( (m n (1 m)) (lst nil (cons m lst))) ( (zerop m) lst)) 12

Do vs. Do* do: evaluates all vali first and assigns index variables in parallel > (setq n 3) 3 > (do ( (m n (1 m)) (x nil (cons m x))) ( (zerop m) x)) (1 2 3) do*: Evaluation of vali and assignment to vari are done in sequential order > (do* ( (m n (1 m)) (x nil (cons m x))) ( (zerop m) x)) (0 1 2) 13

Iteration other functions dolist: iterates over elements of a list (dolist (var list val return val) form1 form2...) In each iteration, var is assigned with a value from list of values list val, Loops over formi, until all done. Then return val is returned. dotimes: iteration over integer values up to a limit (dotimes (var stop val return val) form1 form2...) Initializes var to 0, In each iteration formi are evaluated var is increased by 1, until it reaches stop val, at which point return val is returned. 14

Example Searching for a certain element in a given list (setq mylist (1 2 3 4 5)) (setq srch 2) (dolist (i mylist nil) (cond ((equal i srch) (return t)))) What will be returned in above case? Answer. T will be returned, since 2 exists in mylist. Note: dolist goes through elements of the list without the need for us to explicitly use car and cdr 15

Example Delete the first n items from a list (setq mylist (1 2 3 4 5)) (setq n 2) (dotimes (i n mylist) (setq mylist (cdr mylist))) What will be returned in above case? Answer. (3 4 5) will be returned. 16

Iteration vs. Recursion Example: Reversing a list Using iteration: (defun do rev(lst) (do ((x lst(cdrx)) (result nil (cons (car x) result))) (null x) result))) Using recursion: Cannot add to the end of a list We therefore use an extra variable (accumulator) More overhead due to recursive calls (defun rev2 (lst acc) (cond ((null lst) acc) ( t (rev2 (cdr lst) (cons (car lst) acc))) )) (defun reverse(lst) (rev2 lst nil)) 17