## Saturday, September 24, 2011

### Infinite Lists in Python

In my previous post I discussed infinite lists in Haskell. As it happens the concept may be useful beyond it. As we saw before, using them may yield nice and concise definitions for series. In this post I'm going to show you one way to port the concept to Python.

Initial Port

In Haskell we define naive infinite lists using [1,2..] kind of syntax. I decided to use a class based syntax to mimic this. This particular snippet would be written as InfList(1, 2) in this scheme. The same works for negative numbers as well. You could write InfList(-1, -2) and expect that to work as well.

So what does "InfList(1, 2)" actually do? Consider the following example showing some initial tests of mine:

As you can see once you instantiate the object, you'll have access to its content just like in the case of a regular list. It calculates the values needed on demand. In other words it's lazy.

The example above also showcases the use of lambdas (fibo) and Python's slice syntax. The implementation infers the rule used to generate the series by default. If you want, you can provide a custom lambda that can be used instead. The slice syntax allows you to mimic Haskell's "take".

Besides the aforementioned functionality I ended up implementing __unicode__ just to make it easier to see the first items of the list.

I've listed the actual implementation below. Overall it ended up being surprisingly simple.

Extra Functions

Just having a way to access list items isn't enough. In my previous post I used "zip" and "concat" to combine multiple infinite lists. It's also handy to be able to map and filter the lists. In order to do this I ended up implementing little wrappers for these operations. I've listed the implementation and some tests below.

As you can see there's some overhead. I do think these kind of functions yield some extra power to the concept overall. There are many ways to combine these.

Conclusion

I hope this post gave you some idea on how to implement infinite lists in your favorite programming language. I've no doubt it would be pretty easy to port the concept to say JavaScript, PHP or Ruby. I think the main advantage of the concept is the concise syntax it allows. Pythonistas might want to check out the itertools module for more powerful tools such as this.