Missing the functional mind set

Michael Chermside mcherm at destiny.com
Wed Mar 7 00:34:46 CET 2001


WARNING:

  SPOILERS INCLUDED!

  (well, since the original poster asked for hints not answers,
   I figured it'd be polite to do this)

















Okay, as Erik Francis (and others, I think) point out, sort() is a
modify-in-place method.

So what we need is a functional version (ie, a version that returns
a new value and doesn't modify its argument) for use in functional
programming. Here's one way to write it:

>>> def mysort(list):
        newlist = list[:]
        newlist.sort()
        return newlist

And now I can solve the original problem in a "functional" fashion:

>>> d = {3: 'd', 2: 'b', 1: 'a', 0: 'z', 938302: 'w'}
>>> templist = [ d[key] for key in mysort( d.keys() ) ]
>>> templist
['z', 'a', 'b', 'd', 'w']

Now, I don't recommend this as being the most efficent way to code
the thing, but the Daniel was originally trying to teach himself
the functional technique. And you have to admit, that it's really
quite readable. This is one of the nice things about functional
techniques.

Good luck Daniel... it's ALWAYS useful to try learning new programming
techniques, they increase the number of tools in the toolkit.

-- Michael Chermside




More information about the Python-list mailing list