Comment on Draft Pep ver 4 -- Psuedo Deprecations of Builtins

Sandy Norton sandskyfly at hotmail.com
Wed May 1 12:56:13 EDT 2002


"Raymond Hettinger" <python at rcn.com> wrote in message 

> ... we can publish a short, clean list of built-ins; create new
> modules for functionals and iterttools; and go on merrily as if the language
> had been truly cleaned....

I'm all for a 'functionals' module ... don't particularly think much
about messing with any builtins prior to mystical python 3.0... in the
meanwhile here's a partial (and perhaps buggy) translation of a bunch
of haskell prelude functions to augment your current efforts in this
field. (-:

PS: I initially took up this exercise to test the utility of doctest
(great stuff indeed!)

regards,

Sandy

'''functionalism.py

A useful set of functions for use in functional programming. 
Most are directly translated from haskells standard prelude library.
'''

# sequence operations
head = lambda seq: seq[:1]
tail = lambda seq: seq[1:]
init = lambda seq: seq[:-1]
last = lambda seq: seq[-1:]

# conditional as expression
If = lambda condition, x, y: (condition and [x] or [y])[0]
unless = lambda condition, x, y: (not condition and [x] or [y])[0]


# misc functions
def sequence(func_lst):
    '''sequentially executes a list of thunks (functions without args)
    return the results as a list
    
    >>> sequence([lambda:1, lambda:2])
    [1, 2]
    '''
    do_it = lambda f: f()
    return map(do_it, func_lst)

def reverse(sequence):
    '''returns reverse of a given sequence
    
        >>> reverse('abcdef')
        'fedcba'
    '''
    lst = list(sequence)
    lst.reverse()
    if isinstance(sequence, str): return ''.join(lst)
    elif isinstance(sequence, list): return lst
    elif isinstance(sequence, tuple): return tuple(lst)
    
    
def flip(func, *args):
    '''applies its arguments in reverse order to func
    
        >>> flip(lambda x,y,z: x*y+z, 1,2,3)
        7
    '''
    args = list(args)
    args.reverse()
    return apply(func, args)


def until(condition, function, x):
    '''returns the result of applying x to function until condition
holds.
    
        >>> until(lambda x: x>3, lambda x: x+2, 0)
        4
    '''
    while 1:
        x = function(x)
        if condition(x): break
    return x

def take(n, sequence):
    '''applied to a sequence, returns the first n items of the
sequence,
    
        >>> take(3, [1,2,3,4,5])
        [1, 2, 3]
    '''
    if not sequence or not n: return []
    if n > 0:
        return sequence[:n]

def drop(n, sequence):
    '''applied to a sequence, return the sequence minus the first n
items
    
        >>> drop(2, "abcd")
        'cd'
    '''
    if not sequence or not n: return []
    if n > 0:
        return sequence[n:]

        

def takeWhile(predicate, list):
    '''returns longest list (possibly empty) of elements in 'list'
satisfying 'predicate'
        
        >>> takeWhile(lambda x: x>3, [1,2,3,4,5,6])
        [4, 5, 6]
    '''
    result = []
    for x in list:
        if predicate(x): 
            result.append(x)
    return result
        
def dropWhile(predicate, list):
    '''returns longest list (possibly empty) of elements in 'list' not
satisfying 'predicate'
    
        >>> dropWhile(lambda x: x>3, [1,2,3,4,5,6])
        [1, 2, 3]
    '''
    result = []
    for x in list:
        if predicate(x): continue
        else: result.append(x)
    return result        

def span(predicate, list):
    '''Equivalent to (takeWhile(predicate, list), dropWhile(predicate,
list))
    
        >>> span(lambda x: x>3, [1,2,3,4,5,6])
        ([4, 5, 6], [1, 2, 3])
    '''
    return ( takeWhile(predicate, list), dropWhile(predicate, list) )


def any(predicate, list):
    '''Applied to a predicate and a list, any determines if 
        any element of the list satisfies the predicate.
    
        >>> any(lambda x: x>2, [1,2,3,4])
        1
    '''
    for item in list:
        if predicate(item): return 1
    return 0

def all(predicate, list):
    '''Applied to a predicate and a list, any determines if 
        all elements of the list satisfy the predicate.
    
        >>> all(lambda x: x>2, [3,4,5,6])
        1
    '''
    for item in list:
        if not predicate(item): return 0
    return 1


def sum(lst):
    '''compute the sum of a finite list of numbers.
    
        >>> sum([1,2,3,4,5,6])
        21
    '''
    return reduce(lambda x,y: x+y, lst)

def product(lst):
    '''compute the product of a finite list of numbers.
    
        >>> product([1,2,3,4,5,6])
        720
    '''
    return reduce(lambda x,y: x*y, lst)

    
def zipWith(func, *args):
    '''zips with the function given as the first argument.
    
        >>> zipWith(lambda x,y: x+y, [1,2], [3, 4])
        [4, 6]
    '''
    result = []
    zipped = zip(*args)
    for arg in zipped:
        obj = apply(func, arg)
        result.append(obj)
    return result

def unzip(items):
    '''returning list of tuples reversing zip operations
    
        >>> unzip(zip(range(10), range(10)))
        [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8,
9)]
    '''
    return apply(zip, items)

# string manipulation

def lines(txt):
    '''splits string into list according to new lines
    
        >>> lines("hello my friend\\nThis is wierd.")
        ['hello my friend', 'This is wierd.']
    '''
    return txt.split('\n')

def words(txt):
    '''splits string into list of words according to spaces

        >>> words("hello my friend, how are you?")
        ['hello', 'my', 'friend,', 'how', 'are', 'you?']
    '''
    return txt.split()

def unlines(list):
    '''reverses lines
    '''
    '\n'.join(list)

def unwords(list):
    '''reverses words
    '''
    ' '.join(list)

###################################################
# see http://groups.google.com/groups?hl=en&safe=off&threadm=sXKY7.31790%24Zg2.3194928%40news11-gui.server.ntli.net&rnum=1&prev=/groups%3Fq%3Dfoldr%2Bgroup:comp.lang.python.*%26hl%3Den%26safe%3Doff%26selm%3DsXKY7.31790%2524Zg2.3194928%2540news11-gui.server.ntli.net%26rnum%3D1
# for fold* examples...
###############################################

def _test():
    import doctest, functionalism
    return doctest.testmod(functionalism)

if __name__ == '__main__': _test()



More information about the Python-list mailing list