Classical FP problem in python : Hamming problem

Nick Craig-Wood nick at craig-wood.com
Thu Jan 27 04:30:01 EST 2005


Francis Girard <francis.girard at free.fr> wrote:
>  Thank you Nick and Steven for the idea of a more generic imerge.

You are welcome :-)  [It came to me while walking the children to school!]

[snip]
>  class IteratorDeiterator:
>    def __init__(self, iterator):
>      self._iterator = iterator.__iter__()
>      self._firstVal = None ## Avoid consuming if not requested from outside
>                            ## Works only if iterator itself can't return None

You can use a sentinel here if you want to avoid the "can't return
None" limitation.  For a sentinel you need an object your iterator
couldn't possibly return.  You can make one up, eg

       self._sentinel = object()
       self._firstVal = self._sentinel

Or you could use self (but I'm not 100% sure that your recursive
functions wouldn't return it!)

>    def __iter__(self): return self
> 
>    def next(self):
>      valReturn = self._firstVal
>      if valReturn is None:

and
       if valReturn is self._sentinel:

>        valReturn = self._iterator.next()
>      self._firstVal = None

       self._firstVal = self._sentinel

etc..

[snip more code]

Thanks for some more examples of fp-style code.  I find it hard to get
my head round so its been good exercise!
-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list