CSE 505 -- Smalltalk Mini-Exercises -- Answer Key

  1. Write a Smalltalk expression to return true if x is either equal to 0 or if 10 divided by x equals y.
  2. x=0 or: [10/x=y]
    

  3. Let a be an array of some sort. Write a loop that prints every second element on an output stream strm.
      | a strm |
      strm := WriteStream with: (String new: 100).
      a := Array new: 10.
      a at: 1 put: 'fee fi fo fum'.
      a at: 2 put: 3.14159.
      a at: 3 put: 8.
      "THE FOLLOWING LINE IS THE ONLY NEW PART"
      1 to: a size by: 2 do: [:i | (a at: i) printOn: strm].
      strm contents
    

  4. Add a repeatUntil control structure to Smalltalk. Hint: this is trivial -- do it by defining a repeatUntil: method for BlockContext.

    Add this method to BlockContext:

    repeatUntil: doneTest
      self value.
      doneTest whileFalse: self.
    
    Or if you wanted to define it primitively, without using while, the following will work. (It is less efficient, but maybe more interesting.)
    repeatUntil: doneTest
      self value.
      doneTest value ifFalse: [self repeatUntil: doneTest]
    
  5. Consider the following Smalltalk class definition.
    Object subclass: #Octopus
       instanceVariableNames: 'myblock'
       classVariableNames: ''
       poolDictionaries: ''
    
    setValue: x
       myblock := [x].
    
    setBlock: y
       myblock := y.
    
    getValue
      ^ myblock value
    
    What is the result of evaluating the following code? (The value in each case will be the value of the last o getValue expression.)
          | o a |
       a := 3.
       o := Octopus new.
       o setValue: a.
       a := a+1.
       o getValue
    
    Answer: 3

    And what about this code?

          | o a b |
       a := 3.
       b := [a].
       o := Octopus new.
       o setBlock: b.
       a := a+1.
       o getValue
    
    Answer: 4