Pythonで無限リスト(をやろうとして失敗)

30分プログラム、その353。itertoolsを試してみる。
Pythonのライブラリを眺めてたら、SMLとHaskellを参考にしました、と書いてある素敵なモジュールを見つけたので試してみた。
使ってみた感想としては、相当クセが強い。HaskellやSMLのプログラミング方法がそのまま使えるわけじゃない。一応、使わない要素は評価されないようになってるけど、ちょっと間違えると簡単に評価されてしまう。

使い方

$ python sieve.py
...
  File "sieve.py", line 31, in sieve
    sieve(ifilter(lambda x: x % p != 0,xs)))
  File "sieve.py", line 29, in sieve
    p = ihead(xs)
  File "sieve.py", line 21, in ihead
    x = list(islice(xs,1))
RuntimeError: maximum recursion depth exceeded

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# sieve.py -
#
# Copyright(C) 2008 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2008/08/23 22:19:34
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#
from itertools import *

# 整数の無限列
ints = count(2)

def ihead(xs):
    x = list(islice(xs,1))
    return x[0]

def id(x):
    print "called: ",x
    return x

def sieve(xs):
    p = ihead(xs)
    return chain([p],
                 sieve(ifilter(lambda x: x % p != 0,xs)))

ints = count(2)
primes = sieve(ints)