Reputation: 1820
So for splitting a number into its digits I found this code
def split(n: Int) = if (n == 0) List(0) else {
(Stream.iterate(n)(_/10)takeWhile(_!=0)map(_%10)toList) reverse
}
which works but I couldn't explain to myself how the computation flows . Could anyone provide more insight into the intermediate steps it takes to go from
split(123)
List[Int] = List(3,2,1)
It seems fairly straightforward but reading the method declarations and trying to work examples with calculator I failed to re-create myself the result.
Upvotes: 2
Views: 2072
Reputation: 6385
Let's separate it into a stages:
(Stream.iterate(n)(_/10) // n - is first number, _/10 is function that recursively applied on given number
takeWhile(_!=0) // while result is not equal to 0
map(_%10) // got a list of numbers and take it by mod 10
toList) // transform to list
reverse // take it in reverse order
scala> (Stream.iterate(123)(_/10)).takeWhile(_!=0).toList
res6: List[Int] = List(123, 12, 1)
Upvotes: 3