80 likes | 186 Views
Programming Paradigms. CPSC 449 Week 3-2 Prepared by : Mona Hosseinkhani , Arash Afshar Winter 2014. Department of Computer Science, University of Calgary. Defining range of list. Other ways of defining lists of numbers, chars and other enumerated types
E N D
Programming Paradigms CPSC 449 Week 3-2 Prepared by : Mona Hosseinkhani, ArashAfshar Winter 2014 Department of Computer Science, University of Calgary
Defining range of list • Other ways of defining lists of numbers, chars and other enumerated types • Single step: [n .. m] • [1..5] = [1,2,3,4,5] • ['c'..'g'] = ['c', 'd', 'e', 'f', 'g'] = "cdefg“ • Customizable step: [n, p .. m] • [1,4..20] = [1,4,7,10,13,16,19] • ['c', 'e'..'k'] = ['c', 'e', 'g', 'i', 'k'] = "cegik"
fastFib • Review simple implementation • fib n | n == 0 = 0 | n == 1 = 1 | n > 1 = fib (n-1) + fib (n-2) • fib 7 = (fib 6) + (fib 5) = (fib 5) + (fib 4) + (fib 5) • Better way: Compute Fib of a number, only once • Use Pairs
fastFib (cont.) • Implementation: • At each step, fib adds two numbers: (u, x) • Consider these steps: • (0,1), (1,1), (1,2), (2,3), (3,5), … • Pay close attention to the first element of each pair fibStep :: (Integer,Integer) -> (Integer,Integer) fibStep (u,v) = (v,u+v)
fastFib (cont.) • Construct the sequence of pairs: • fibPair :: Integer -> (Integer,Integer) • fibPair n | n==0 = (0,1) | otherwise = fibStep (fibPair (n-1))
fastFib (cont.) • Finally, define fastFib as bellow: • fastFib :: Integer -> Integer • fastFib = fst . fibPair • note that, as the previous implementation of fib, this function does not print the whole series: • fastFib 7 = 13, not 0,1,1,2,3,5,8,13
Library Documentations • Mac • file:///usr/share/doc/ghc/html/ • Ubuntu: • /usr/share/doc/ghc • Windows: • documents are found in Haskell Platform program groups • http://www.haskell.org/hoogle/
Question hossem@ucalgary.ca