\documentstyle[11pt]{article}
\nofiles
\input{use-full-page}
\input{programs}

\begin{document}

\title{A Little Smalltalk Example}
\author{Gary T. Leavens \\
Department of Computer Science, 229 Atanasoff Hall \\
Iowa State University, Ames, Iowa 50011-1040 USA \\
leavens@cs.iastate.edu
}
\maketitle

\begin{abstract}
An example of a Little Smalltalk program, and how to run it.
\end{abstract}

\section{The Problem}

Imagine that the state has just decided to start a lottery.
The governor appoints as head of the lottery a former computer-scientist
turned bureaucrat who
happens to know simulation and object-oriented design.
The governor favors a lottery where players pick ``seven numbers
and the winnings are based on how many match the state's chosen numbers.''
The state law mandates that half of the money bet on the lottery should
be kept by the state (on average).
Tickets will cost a dollar each.

The new head of the lottery wants to ensure that each customer will,
on the average, win {\em something\/} at least once in twenty bets.
She believes that customers do not win anything after placing forty
bets they will stop playing (and she will be out of a job).

Since the head of the lottery knows Smalltalk better than probability theory,
she decides to write a simulation program.
Some thought yields the following parameters that may be varied
in different runs of the simulation.

\begin{itemize}
\item
The range of numbers the players pick (e.g., 1 to 42).

\item
Whether or not the player can choose the same number more than once.

\item
A mapping that gives the amount of a player's winnings
according to the number of numbers that match the state's chosen numbers.

\item
The probability distribution used by players to choose their numbers.
(It seems clear that the state should use a uniform distribution,
but players might tend to favor certain numbers, such as 7 and 11.)

\item
How many losses a player will sustain before giving up.
\end{itemize}

It is decided that the program should calculate
the expected value of a one dollar bet (to check that it is fifty cents),
and that the program will simulate several customers placing different
numbers of bets,
to check the constraint that customers are likely to win any bets after twenty
bets and are almost sure to win something after forty bets.

For the first version of the program, it is to be assumed that the
customers choose numbers uniformly
and that all numbers chosen for a bet must be distinct.

Actions in the program should therefore allow the user to
define the range of numbers, define the payoff table,
create customers,
tell them to place a number of bets, and report their losses (or winnings).

\section{The Design}

The concepts and things in this problem are lottery tickets,
the winning numbers,
choosing (7) distinct numbers from a uniform distribution,
money, the lottery agency
(which chooses the range of numbers, and the payoff table),
and the customer (who picks the numbers on tickets).

It seems useful to represent the winning numbers as a special kind of ticket.
Distinguishing the winning number selection from the customer selection
allows customers to pick from a skewed distribution.
Making the discrete uniform probability distribution an object will help
keep down the size of the code and ensure that there is only one random
number generator in use.
(In little Smalltalk, {\tt Random new next} will give different random numbers
each time, but this ``feature'' seems highly implementation dependent.)
On the other hand, having a separate class for money seems like overkill,
so we just use numbers to represent money.

The class {\tt Ticket} will have as its abstract values, a set of seven
distinct integers.  It provides the operations of the class {\tt Collection}
and an initialization operation.

The class {\tt WinningTicket} will be a subtype of {\tt Ticket}
and have an extra operation that compares a ticket and returns the number
of matches.

It is possible to specify probability distributions in a very general framework
(see for example, Goldberg and Robinson's Book
{\em Smalltalk-80: The Language and its Implementation}, chapter 21).
For the sake of brevity we settle for something simplier:
a class {\tt UniformDiscrete}, whose abstract value is a stream of
random integers from 1 to a given size.
We will have an operation to return a random integer from the stream
and a special operation to return a set of $n$ such numbers without duplicates.

The classes {\tt Lottery} has as its abstract value,
the range of numbers that can be chosen on tickets,
the payoff table, and
the set of winning numbers
(i.e., a {\tt WinningTicket}).
It has operations that allow the winnings of a ticket to be calculated.

Finally, the class {\tt LottoCustomer} will have as its abstract value
a list of tickets, and money representing its loss or gain.
It will have an operation to report its winnings (or loss).

The implementations of these classes follows.

\section{Implementation}

\subsection{Ticket}

The class {\tt Ticket} is simply a subclass of {\tt Collection}.
Its representation is a {\tt Set} of seven integers, stored in the instance
variable {\tt rep}.
\begin{verbatim}
Collection addSubClass: #Ticket instanceVariableNames: 'rep'
\end{verbatim}
One cannot create a ticket and initialize it in one step,
since in Little Smalltalk the instance creation operation {\tt new} takes
no arguments
(and cannot be changed, since there are no class methods as in ST-80).
Also note that in the method initialize: we extract the elements of the
argument so that the value of the instance variable is not pointing to an
object that is outside the control of this class.
(Not doing this would be called ``exposing the representation''.)
\begin{verbatim}
new
    rep <- Set new

initialize: aSet
    "REQUIRES: aSet has seven integers"
    "EFFECT: this ticket has seven distinct integers"
    rep addAll: aSet

do: aBlock
    ^ rep do: aBlock

copy
    ^(self class new) initialize: rep
\end{verbatim}

\subsection{Winning Ticket}

The class {\tt WinningTicket} is a subclass of {\tt Ticket}.
\begin{verbatim}
Ticket addSubClass: #WinningTicket instanceVariableNames: ''
\end{verbatim}
It simply adds the following method,
which allows other tickets to be compared with this winner.
\begin{verbatim}
matches: aTicket
    "EFFECT: return the number of matches between self and aTicket"
    ^ aTicket inject: 0 into: [ :n :elem | n + (self occurrencesOf: elem) ]
\end{verbatim}
This method is where the most time is spent in the program,
since it takes 49 comparisons to determine the matches of each ticket.
Faster algorithms are left to the reader.

\subsection{Uniform Discrete}

The class {\tt UniformDiscrete} is a subclass of {\tt Object}.
It has an instance variable {\tt rand}, which is an instance of class 
{\tt Random} and an instance variable {\tt size}, which is the maximum
size of number it generates.
\begin{verbatim}
Object addSubClass: #UniformDiscrete instanceVariableNames: 'rand size'
\end{verbatim}
The size defaults to 42.
\begin{verbatim}
new
    rand <- Random new.
    size <- 42

size: anInteger
    size <- anInteger

next
    ^rand randInteger: size

pick: anInteger
    "REQUIRES: anInteger <= size"
    "EFFECT: returns a set with anInteger distinct random integers
     from 1 to size"
    | s |
    s <- Set new.
    [ (s size) < anInteger ] whileTrue: [ s add: (self next) ].
    ^s
\end{verbatim}

\subsection{Lottery}

The class {\tt Lottery} is a subclass of {\tt Object}, although one might
consider making it a subclass of some of the other classes above.
\begin{verbatim}
Object addSubClass: #Lottery instanceVariableNames: 'wt prizes range ud'
\end{verbatim}
It has instance variables: {\tt wt} (a {\tt WinningTicket})
{\tt prizes}, which is an array of numbers giving the payoffs (in dollars)
for each number of matches,
{\tt range}, which is an integer giving the upper bound on the numbers that
can be chosen,
and {\tt ud}, an instance of {\tt UniformDiscrete}.

The {\tt new} of class Lottery method initializes all the instance variables.
The methods {\tt range:}, {\tt range}, {\tt winningTicket},
{\tt payoffs}, and {\tt payoffs:} are typical of methods
that give clients access to instance variables of a class.
Note how mutable objects are copied before being released to callers
of {\tt winningTicket} and {\tt payoffs};
this prevents the caller from having a pointer into the representation
of the object.
\begin{verbatim}
new
    | ud |
    "(prizes at: i) is the amount of money won by matching i numbers"
    prizes <- #(0.0 0.0 0.0 1.0 10.0 1000.0 10000000.0).
    wt <- WinningTicket new.
    ud <- UniformDiscrete new.
    range <- 42.
    ud size: range.

range: anInteger
    "REQUIRES: anInteger > 0"
    ud size: anInteger.
    range <- anInteger

range
    ^ range

winningTicket
    ^wt copy

payoffs: anArray
    "REQUIRES: anArray contains seven numbers"
    prizes <- anArray copyFrom: 1 to: (anArray size)

payoffs
    ^ prizes copyFrom: 1 to: (prizes size)
\end{verbatim}

The following methods, also instance methods of class {\tt Lottery},
do more interesting things.
The method {\tt pickWinner} picks a winning ticket.
The method {\tt winnings:} tells how much money was won by the given ticket.
\begin{verbatim}
pickWinner
    wt initialize: (ud pick: 7)

winnings: aTicket
    "EFFECT: return the amount of money won by aTicket"
    | m |
    m <- wt matches: aTicket.
    (m = 0) ifTrue: [ ^0.0 ] ifFalse: [^prizes at: m]
\end{verbatim}

\subsection{Lotto Customer}

The class {\tt LottoCustomer} is a subclass of {\tt Object}.
It has instance variables {\tt tickets} (a list of tickets),
{\tt winnings} (a number), {\tt maxLoss} (a number),
and {\tt lottery} (a {\tt Lottery} instance),
which enables customers to share the lottery.
\begin{verbatim}
Object addSubClass: #LottoCustomer \
  instanceVariableNames: 'tickets winnings lottery maxLoss'
\end{verbatim}
The {\tt maxLoss} variable tells how much the customer is willing to lose.
\begin{verbatim}
new
    tickets <- List new.
    maxLoss <- -40.
    winnings <- 0.0.

tickets
    ^List new addAll: tickets

winnings
    "EFFECT: return the amount of money won"
    ^winnings

lottery: aLottery
    lottery <- aLottery

lottery
    ^ lottery

maxLoss: aNumber
    maxLoss <- aNumber

maxLoss
    ^maxLoss

play: numTimes
    | ud t |
    ud <- UniformDiscrete new.
    numTimes timesRepeat:
          [ (winnings < maxLoss) ifTrue: [^self].
            self playTicket: ((Ticket new) initialize: (ud pick: 7))]

playTicket: aTicket
    tickets add: aTicket.
    winnings <- winnings - 1 + (lottery winnings: aTicket)
\end{verbatim}

\subsection{Tracing Lotto Customer}

For purposes of debugging, it is often useful to make a subclass.
The subclass {\tt TracingLottoCustomer} is just like {\tt LottoCustomer},
except that its {\tt playTicket:} method prints debugging information.
\begin{verbatim}
LottoCustomer addSubClass: #TracingLottoCustomer \
   instanceVariableNames: ''
\end{verbatim}
Note that the method {\tt playTicket:} is overridden in this subclass.
By using {\tt super}, it is able to reuse the code of the superclass
{\tt LottoCustomer} without change,
hence there is no question that when the debugging is finished,
the method of class {\tt LottoCustomer} will work as expected.
\begin{verbatim}
playTicket: aTicket
   super playTicket: aTicket.
   ('picked ticket: ', aTicket printString) print.
   self winnings print
\end{verbatim}

\section{Running the Program}

It is convenient when building a program composed of several classes,
to make a class whose sole purpose is to read in the other classes.
In this program, that class is called {\tt LoadLottery}.
\begin{verbatim}
Object addSubClass: #LoadLottery instanceVariableNames: ''
\end{verbatim}

The method {\tt new}, besides creating an object of class {\tt LoadLottery},
has the side effect of filing in all the files that make up the lottery system.
The method {\tt dump} is used when changes are made through the editor
during the process of debugging; it produces the files read in by {\tt new}.
\begin{verbatim}
new
    |f|
    f <- File new.
    f fileIn: 'Ticket.st'.
    f fileIn: 'WinningTicket.st'.
    f fileIn: 'UniformDiscrete.st'.
    f fileIn: 'Lottery.st'.
    f fileIn: 'LottoCustomer.st'.
    f fileIn: 'TracingLottoCustomer.st'

dump
    Ticket fileOut.
    WinningTicket fileOut.
    UniformDiscrete fileOut.
    Lottery fileOut.
    LottoCustomer fileOut.
    TracingLottoCustomer fileOut
\end{verbatim}

To run the simulation, one first creates an instance of the class {\tt Lottery}
and initializes the range and payoffs.
One then creates a customer.
The customer can then be asked to play the lottery and report winnings.
It is convenient to put an example of all this in a method of the class
{\tt LoadLottery}, so that this class contains information about the
entire system.  In the {\tt example} method, the line that creates a normal
customer is commented out.
\begin{verbatim}
example
    | l cust |
    l <- Lottery new.
    l range: 30.
    l payoffs: #(0.0 1.0 10.0 100.0 1000.0 10000.0 1000000.0).
    "cust <- (LottoCustomer new) lottery: l."
    cust <- (TracingLottoCustomer new) lottery: l.
    l pickWinner.
    cust play: 50.
    cust winnings print
\end{verbatim}

Running the entire system is then done by typing the following code in
to the interpreter, in a directory where the files used by the
{\tt LoadLottery} method {\tt new} are found.
(Note that the interpreter does not like it if you type a period (.)
at the end of each line.)
\begin{verbatim}
File new fileIn: 'LoadLottery.st'
ll <- LoadLottery new
ll example
\end{verbatim}

\end{document}
