Ounce Of Mathematics

prof. Brian Harvey used to say "an ounce of mathematics is worth pound of computer science".

There is how. In famous Peter Norvig's course (on udacity) there is a small sub-task to write a tiny predicate procedure, which returns True if a hand of cards has the same suit.

Like a good student of CS61A I wrote this pile of functional-style code:

def flush(hand):
    suits = [s for r,s in hand]
    return reduce(lambda x, y: x and y, map(lambda a: a[0] == a[1],
                                     zip(suits, suits[1:])))

What could possibly go wrong? You could visualize how beautifully a list zips with itself (strictly via references, no data copied!) and how a new list of Booleans is going to be produced, to be folded then into a single value. You could see the flow and all the wonders.

Here is the Norvig's snippet

def flush(hand):
    suits = [s for r,s in hand]
    return len(set(suits)) == 1

What the ...? Well, the set-from-a-list constructor removes all duplicates (due to the nature of a Math set), so if the length of a resulting set is 1, then all elements of a list were the same value.

But, but we know how to make a set ADT out of conses and write short-circuiting and or every? for sequences.))

Comments

No comments.