Functional Python Programming

(Wang) #1
Chapter 14

The preceding function will generate a pair of dice for us.


Here's our expectation from the overall game:


def craps():


outcome= Just(("",0, []) ) >> come_out_roll(rng) >> point_roll
(rng)


print(outcome.getValue())


We create an initial monad, Just(("",0, [])), to define the essential type we're
going to work with. A game will produce a three tuple with an outcome, a point,
and a sequence of rolls. Initially, it's a default three tuple to define the type we're
working with.


We pass this monad to two other functions. This will create a resulting monad,
outcome, with the results of the game. We used the >> operator to connect the
functions in the specific order they must be executed. In an optimizing language,
this will prevent the expression from being rearranged.


We get the value of the monad at the end using the getValue() method. Since the
monad objects are lazy, this request is what triggers the evaluation of the various
monads to create the required output.


The come_out_roll() function has the rng() function curried as the first argument.
The monad will become the second argument to this function. The come_out_roll()
function can roll the dice and apply the come out rules to determine if we have a
win, a loss, or a point.


The point_roll() function also has the rng() function curried as the first
argument. The monad will become the second argument. The point_roll()
function can then roll the dice to see if the bet is resolved. If the bet is unresolved,
this function will operate recursively to continue looking for resolution.


The come_out_roll() function looks like this:


@curry


def come_out_roll(dice, status):


d= dice()


if sum(d) in (7, 11):


return Just(("win", sum(d), [d]))


elif sum(d) in (2, 3, 12):


return Just(("lose", sum(d), [d]))


else:


return Just(("point", sum(d), [d]))

Free download pdf