Of what use is 'lambda'???

Kragen Sitaker kragen at dnaco.net
Tue Sep 26 14:32:36 EDT 2000


In article <39d09df6.11689247 at news.bright.net>,
Jonadab the Unsightly One <jonadab at bright.net> wrote:
>ge at nowhere.none (Grant Edwards) wrote:
>> Which means that you can not do things like like file-system or
>> network operations (or even console I/O) in a strictly
>> functionaly language.   Right?
>
>That was the obvious conclusion I made.  Well, in a *purely*
>functional language.  (Apparently "strict" has a special 
>nonstandard meaning for functional programmers...)

Right.  The real world isn't functional; it has state and side effects,
and when you interact with it, you introduce state and side effects
into your program.

It's still possible to write the internals of your program
functionally.  You can do things like have a "real world" object, and
write functions like print, which takes a real-world object and a
string and returns a new real-world object with the string output to
it.  Then you just have to ensure that you don't try to refer to the
old real-world object again later.

Methods for ensuring this include monads, uniqueness typing, and linear
languages.  I only understand linear languages.

"Strict" languages are those that use applicative-order reduction: they
evaluate the arguments to a function before calling the function.
Essentially all nonfunctional languages are strict.  There are some
functional languages that are purely non-strict --- known as "lazy" ---
and you can add non-strict functionality to any language.  Lazy
evaluation means you don't do the computation to compute a value until
you need it for something else.

Here's a lazy Python sequence of squares:
class Map:
    def __init__(self, func):
        self.func = func
        self.cache = []
    def __len__(self):
        raise TypeError, "len() of infinite list"
    def __getitem__(self, key):
        curlen = len(self.cache)
        if curlen <= key:
            for i in range(curlen, key+1):
                self.cache.append(self.func(i))
        return self.cache[key]
    # needed in 1.5.2
    def __getslice__(self, start, end):
        # Map doesn't support finite sequences; so we use a list
        rv = []  
        for i in range(start, end):
            rv.append(self[i])
        return rv

squares = Map(lambda x: x * x)

print squares[5:10]

In a purely strict world, you can't throw around things like the
infinite sequence of squares.  But with a little laziness, you can do
stuff like that.  More interesting sequences, like the infinite series
of primes, can be dealt with lazily too.
-- 
<kragen at pobox.com>       Kragen Sitaker     <http://www.pobox.com/~kragen/>
Perilous to all of us are the devices of an art deeper than we ourselves
possess.
                -- Gandalf the Grey [J.R.R. Tolkien, "Lord of the Rings"]



More information about the Python-list mailing list