chapter6 - PROGRAMMING IN HASKELL...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon
1 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 Introduction As we have seen, many functions can naturally be  defined in terms of other functions. factorial  :: Int   Int factorial n = product [1. .n] factorial maps any integer n to the  product of the integers between 1 and n.
Background image of page 2
3 Expressions are evaluated  by a stepwise process of  applying functions to their arguments. For example: factorial 4 product [1. .4] = product [1,2,3,4] = 1*2*3*4 = 24 =
Background image of page 3

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

View Full DocumentRight Arrow Icon
4 Recursive Functions In Haskell, functions can also be defined in terms of  themselves.  Such functions are called recursive . factorial 0     = 1 factorial (n+1) = (n+1) * factorial n factorial maps 0 to 1, and any other  positive integer to the product of itself  and the factorial of its predecessor.
Background image of page 4
5 For example: factorial 3 3 * factorial 2 = 3 * (2 * factorial 1) = 3 * (2 * (1 * factorial 0)) = 3 * (2 * (1 * 1)) = 3 * (2 * 1) = = 6 3 * 2 =
Background image of page 5

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

View Full DocumentRight Arrow Icon
6 Note: factorial 0 = 1 is appropriate because 1 is the  identity for multiplication: 1 * x = x = x * 1. The recursive definition diverges  on integers  <  0  because the base case is never reached: > factorial (-1) Error: Control stack overflow
Background image of page 6
7 Why is Recursion Useful? Some functions, such as factorial, are simpler
Background image of page 7

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

View Full DocumentRight Arrow Icon
Image of page 8
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 06/11/2011 for the course CSCE 330 taught by Professor Valtorta during the Spring '10 term at Columbia SC.

Page1 / 22

chapter6 - PROGRAMMING IN HASKELL...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online