Haskell like (c:cs) syntax
Wed Aug 29 00:27:44 CEST 2007
"Stefan Niemann" <stefan at 3niemann.de> writes:
> Is there a pattern matching construct in Python like (head : tail), meaning
> 'head' matches the first element of a list and 'tail' matches the rest? I
> could not find this in the Python documentation.
Python's lists are actually linear arrays. You can subscript them,
i.e. x is the first element, and slice them, i.e. x[1:] is all
elements after the first. Note that x[1:] actually makes a new
array and copies all the elements of x.
Normally in Python one writes iterative loops rather than recursing
or folding over a list:
for a in x:
so slicing isn't that common.
Python also has something called generators which are sort of like
Haskell's lazy-evaluation lists. They often make it possible to
program in a Haskell-like style. Note however that they are mutable
objects, i.e. using g.next() to get the next element of a generator
actually updates the generator's internal state. This can lead to a
bunch of subtle pitfalls if you're not careful, but overall they are a
very useful feature.
More information about the Python-list