View this PageEdit this PageAttachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide
Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

John Meyer

COWEB ASSIGNMENT 3 IS LOCATED HERE: http://coweb.cc.gatech.edu/cs2340/5408

COWEB ASSIGNMENT 2 IS LOCATED HERE: http://coweb.cc.gatech.edu/cs2340/5379

Midterm Review

Writing Code - Fibonacci Sequence
fib: n
  "returns the nth number in the Fibonacci sequence, or error if number is less than zero"
  "input must be an integer to be valid"
  (n < 0) ifTrue: [self error: 'lessThanZero'].
  (n = 0) ifTrue: [^1].
  (n = 1) ifTrue: [^1].
  (n > 1) ifTrue: [^ ((self fib: (n - 2)) + (self fib: (n - 1))))].



Tracing Code - Rainfall Problem
Line 1: | data onlyPositiveNumbers |
Line 2: data := OrderedCollection withAll: #(1 2 3 -4 -5 'error' 6 -7 999 2).
Line 3: onlyPositiveNumbers := [:i | (i isKindOf: Number) and: [i positive]].
Line 4: data := data select: onlyPositiveNumbers.
Line 5: data := data copyUpTo: 999. "not including"
Line 6: Transcript show: data average

Line 1 declares the temporary - as opposed to class or instance - variables 'data' and 'onlyPositiveNumbers' used in this function.

Line 2 assigns to the variable 'data' the ordered collection between the parentheses, (1 2 3 -4 -5 'error' 6 -7 999 2). Note that 'data' doesn't have a 'type', and the members of the collection may be of any 'type', as that term is used in most programming languages.

Line 3 assigns to the variable 'onlyPositiveNumbers' the code block between the brackets. That code block is to be used on Collections, and iterate through the Collection (using the temporary variable i whose scope is limited to the block) and add to return a new Collection containing only members of the old Collection that are both a Number (i isKindOf: Number) AND positive (i: positive). In short, it returns a Collection of all the positive numbers in the old Collection.

Line 4 assigns to 'data' a subset of the original Collection as determined by onlyPositiveNumbers, that is, (1 2 3 6 999 2). Note that on the right hand side of the assignment operator 'data' receives the message 'select: onlyPositiveNumbers' which, when the onlyPositiveNumbers block is expanded, are the selection criteria to be performed on the original 'data' Collection.

Line 5 assigns to 'data' the contents of the original 'data' Collection up to but not including (unless the person who wrote that comment is a real bastard) 999: (1 2 3 6 2). The syntax is similar to line 4, above.

Line 6 prints to the Transcript average of the collection 'data', or data receives the message 'average', which returns the numerical average of the contents of the Collection 'data'. The Object Transcript, in turn, receives 'show: 2.8', which in turn displays 2.8 on the Transcript.

Ya.

Links to this Page