因此,为了将数字拆分成数字,我找到了这段代码
def split(n: Int) = if (n == 0) List(0) else {
(Stream.iterate(n)(_/10)takeWhile(_!=0)map(_%10)toList) reverse
}
有效,但我无法向自己解释计算的流程。任何人都可以更深入地了解从
开始的中间步骤split(123)
List[Int] = List(3,2,1)
看起来相当简单但是阅读方法声明并尝试使用计算器工作示例我无法重新创建结果。
答案 0 :(得分:3)
让我们把它分成几个阶段:
(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)