80 likes | 234 Vues
Programming Paradigms. CPSC 449 Week 2-2 Prepared by : Mona Hosseinkhani, Arash Afshar Winter 2014. Department of Computer Science, University of Calgary. Local Definitions. Solving a problem in steps: local definitions as a part of function definition Lets start with an example:
E N D
Programming Paradigms CPSC 449 Week 2-2 Prepared by : Mona Hosseinkhani, ArashAfshar Winter 2014 Department of Computer Science, University of Calgary
Local Definitions • Solving a problem in steps: local definitions as a part of function definition • Lets start with an example: • Define a function: f
Local Definitions fourPics1 :: Picture -> Picture fourPics1 pic = left `beside` right where left = … right = … • One way to tackle: Local Definitions fourPics1 :: Picture -> Picture fourPics pic = left `beside` right where left = pic `above` invertColour pic right = invertColour (flipV pic) `above` flipV pic
Calculation with local definitions • The values of the local definitions are calculated beneath the where if their values are needed • Example: sumSquares :: Integer -> Integer -> Integer sumSquares n m = sqN + sqM where sqN = n*n sqM = m*m • Consider the indentation (offside rule) for local definitions after where
let expressions • For making definitions local to an expression vs. functions let x = 3+2 in x^2 + 2*x - 4 letEx1 :: Integer letEx1 = let x = 3+2 in x^2 + 2*x - 4 letEx2 :: Integer letEx2 = let x = 3+2 ; y = 5-1 in x^2 + 2*x - y
Local definitions scopes • Scope of definition: part of the program in which the definition can be used • Example: (Visible in whole code) isOdd, isEven :: Int -> Bool isOdd n | n<=0 = False | otherwise = isEven (n-1) isEven n | n<0 = False | n==0 = True | otherwise = isOdd (n-1)
Local definitions scopes • Local definitions scope: visible in the conditional equation in which they appear • Local definitions can be used before they are defined • Example:
Questions hossem@ucalgary.ca http://www.ucalgary.ca/mhosseinkhani/CPSC449