[Tutor] Letters & Digits [functional programming]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 18 Nov 2001 17:45:36 -0800 (PST)


On Sun, 18 Nov 2001 alan.gauld@bt.com wrote:

> > clean and easy way to test each character in a string to 
> > see if they match (or do not match) characters from those lists. 
> 
> import string
> chars_of_interest = string.lowercase + string.digits
> 
> for c in myString:
>    if c in chars_of_interest: break
>    else: # do something
> 
> You could also use some of the functional programming 
> things like comprehensions or map or filter


One functional function that might be useful is the idea of an "every()"
function that sees if every element in a list passes some test.  For
example, it might be nice to be able to write something like:

###
if every(isEven, [2, 4, 5, 8]):
    print "This can't happen, can it?!"
if every(isPrime, [2, 3, 5, 7]):
    print "These numbers are prime."
###

The nice thing about every() is that it now allows us to test a whole
sequence of things without worrying about loops.  It's a "functional"
approach because we're giving every() a function that tells it what it
means to be a true element.


Here's a sample implementation of the every() function:

###
def every(predicate_function, sequence):
    """Returns 1 if every element in our sequence passes
    through our predicate_function in good shape.  Otherwise,
    return 0."""
    for element in sequence:
        if not predicate_function(element):
            return 0
    return 1
###

and a sample test in the interpreter:

###
>>> def isDigit(s):   
...     return s in ['0', '1', '2', '3', '4', '5', '6',   
...                  '7', '8', '9']   
... 
>>> every(isDigit, "42")
1
>>> every(isDigit, "forty-two")
0
>>> every(isDigit, ['4', '2'])
1
###


Hope this helps!