python equivalent to haskells iterate.

Graeme Caldwell graemercaldwell at yahoo.co.uk
Fri Feb 4 05:40:37 EST 2005


Subject: equivalent to Haskell's iterate function.
 
While reading through "Two Dozen Short Lessons in Haskell". I came across the following function:
 
     decimalNumeralFromInteger x = reverse [d | (s,d) <- takeWhile(/=(0,0)) (sdPairs x)]
     where
           sdPairs x = iterate nextDigit (x `divMod` 10)
           nextDigit(xShifted,d) = xShifted `divMod` 10
 
What this does is takes as a paramter a decimal integer and converts
it to a sequence in which each member is numeral from each position in
the integer.
e.g.
 
                     decimalNumberFromInteger 543654 = [5,4,3,6,5,4]
 
As Python's the language I am most interested in becoming proficient
in(still a way to go) , I rewrote this in Python. I was trying to preserve the functional aspects of the Haskell, and wanted a python function that would let me repeatedly apply a function(lambda or otherwise) to its own result obviously this is easy to do using a while loop but I wanted a more elegant solution,as in the Haskel code  above.
I found that there are plenty of functions that allow one to iterate over a sequence(itertools module), but could not find a equivalent to Haskell's  iterate.
The best that I could come up with was:
    
def decimalNumeralFromInteger(x):
     list = []
     x = divmod(x,10)
     while x <> (0,0):
          list.append(x[1])
          x = divmod(x[0], 10)
     return list
 
which seems a bit clunky by comparison. 
My question is does such a function exist.
 
If the answer is obvious and in the docs, excoriation is expected
and deserved. 
Also I know it's not really an important issue and the
above function is adequate to the task, but I'm curious if it can be
done the Haskell way and if not, why.


		
---------------------------------
 ALL-NEW Yahoo! Messenger - all new features - even more fun!  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20050204/b438a015/attachment.html>


More information about the Python-list mailing list