80 likes | 278 Vues
This document provides an overview of local definitions in function programming, focusing on their role in defining and calculating functions step-by-step. It covers practical examples, such as defining functions using local definitions and calculating values beneath a 'where' clause. The text emphasizes the scope of definitions within the program and the importance of indentation following 'where' and 'let' expressions. Ideal for students of Computer Science at the University of Calgary, it aims to enhance understanding of local definitions.
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