[aklug] Re: Lists

From: Michael Fowler <michael@shoebox.net>
Date: Tue Jul 26 2011 - 14:04:20 AKDT

On Mon, Jul 25, 2011 at 08:55:17PM -0800, Christopher Howard wrote:
> Question for the Perl programmers and the Python programmers: in either
> language, can you re-implement the length function for lists? (Without
> actually using the built-in length function, of course.)

Others have covered Python, so I guess I'll cover Perl.

Haskell lists don't really have a direct equivalent in Perl. In Perl,
lists are transient; you can't modify them, so they are immutable much
as lists in Haskell are, but they also only exist in the statement in
which they are used. For example, you call functions with a list of
arguments, or you initialize an array (or hash) using a list of values.

    foo("this", "is", "a", "list");
    @x = qw( as is this );
    %h = ( this => "too" );

You can get the length of a list, but it has very few practical
applications, and the syntax is.. questionable:

    $c = () = (10, 20, 30);

Generally you use this sort of thing when you want to impose list
context on an operator, but you ultimately just want a count:

    $c = () = "foo" =~ m/[aeiou]/g;
    # $c is 2, as there were two matches

Arrays are similar to Haskell lists (in some uses) in that they are not
transient; they are bound to a variable name. Perl has no operator for
determining the length of an array. You simply evaluate the array in
scalar context:

    $c = @x;
    if (@x >= 10) { say "We have enough!" }

And so on. Whether this means yes or no depends on how you look at it;
you could easily implement a function that simply iterates over the
array, incrementing a counter, achieving the same effect your Haskell
length does. However, the length of an array is something tracked
independently within the data structure that implements arrays (called
an AV).

    perl -MDevel::Peek -wle '@x = qw( a b ); Dump(\@x);'
    ...
      SV = PVAV(0x919f6f0) at 0x91b93b8
        REFCNT = 2
        FLAGS = ()
        ARRAY = 0x91bce38
        FILL = 1
        MAX = 3
        ARYLEN = 0x0
        FLAGS = (REAL)
        Elt No. 0
        SV = PV(0x919c6d8) at 0x919e818
        ...
        Elt No. 1
        SV = PV(0x919c768) at 0x919e9d8
        ...

MAX being the length of the array.

So, implementing such a function yourself is rather silly.

You can also tie arrays, essentially implementing an array with a class.
At that point how you determine length depends entirely on what's
backing the class.

The short answer to your question: maybe.

--
Michael Fowler
www.shoebox.net
---------
To unsubscribe, send email to <aklug-request@aklug.org>
with 'unsubscribe' in the message body.
Received on Tue Jul 26 14:04:51 2011

This archive was generated by hypermail 2.1.8 : Tue Jul 26 2011 - 14:04:51 AKDT