SFTW120-LectureNotes-17

# SFTW120-LectureNotes-17 - SFTW120 Programming Science...

This preview shows pages 1–4. Sign up to view the full content.

1 SFTW120 Programming Science Lecture Notes 17: Lisp: Recursion © Robert P. Biuk-Aghai SFTW120 - Programming Science 2 Lecture Notes 17 Recursion s Recursion is when a function repeats an action by calling itself s Example: (defun factorial (num) (if (= num 0) 1 (* num (factorial (- num 1))))) s Function factorial is called from within function factorial : this is a recursive call s The recursive call starts a new instance of the function from the beginning, the current instance stays in the same location of the function

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 SFTW120 - Programming Science 3 Lecture Notes 17 Example of recursive function calls (defun factorial (num) (if (= num 0) 1 (* num (factorial (- num 1))))) (defun factorial (num) (if (= num 0) 1 (* num (factorial (- num 1))))) (defun factorial (num) (if (= num 0) 1 (* num (factorial (- num 1))))) call call program pointer program pointer program pointer num=2 num=1 num=0 call SFTW120 - Programming Science 4 Lecture Notes 17 What happens in factorial ? Example: (factorial 4) 1 st time: (* 4 (factorial 3)) 2 nd time: (* 3 (factorial 2)) 3 rd time: (* 2 (factorial 1)) 4 th time: (* 1 (factorial 0)) 5 th time: 1 = (* 4 (* 3 (* 2 (* 1 1))))) = 24
3 SFTW120 - Programming Science 5 Lecture Notes 17 Recursive function calls s In recursion, function calls are nested (one is contained inside another one) s Each function call returns a value to the outer function from where it was called factorial 4 24 factorial 3 factorial 2 factorial 1

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 9

SFTW120-LectureNotes-17 - SFTW120 Programming Science...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online