[aklug] Lists

From: Christopher Howard <christopher.howard@frigidcode.com>
Date: Mon Jul 25 2011 - 20:55:17 AKDT

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.)

I was curious, because I was reimplementing various Haskell list
functions (as part of problem solving exercises of the book I'm going
through). This is possible because lists in Haskell are defined by the
regular type rules, and the last element in a list is an empty value
([]). So its just a matter of using a recursive function and pattern
matching:

length [] = 0
length [x] = 1
length (x:xs) = let length' i [a] = i+1
                     length' i (a:as) = length' (i+1) as
                   in length' 1 xs

Another interesting example in the book was reversing a list, without
calculating a length or using index calls (both of which would actually
be less efficient than recursive methods).

-- 
frigidcode.com
theologia.indicium.us
---------
To unsubscribe, send email to <aklug-request@aklug.org>
with 'unsubscribe' in the message body.
Received on Mon Jul 25 20:54:55 2011

This archive was generated by hypermail 2.1.8 : Mon Jul 25 2011 - 20:54:55 AKDT