I have started practicing functional programming in python recently.
Lets say I define a function that gets an array of digits and concatenates it:
In [1]: def fromDigits(digits):
...: return reduce(lambda x,y: 10*x+y,digits,0)
...:
In [2]: fromDigits([1,2,3,4,5])
Out[2]: 12345
Now I want to implement the reverse function:
def toDigits(num):
return unfold(lambda m,digits: (m/10,digits+[m % 10]) if m>0 else None, num, [])
But I couldn't find a definition of unfold
in the python
functools or anywhere in the standard library.
unfold is not a python function ... here is a recursive solution ...
def to_digits(x):
if not x: return []
return to_digits(x//10) + [x%10]
to_digits(12345)