Haskell中的反向功能行为
digits :: Int -> [Int]
digits n = reverse (x)
where x
| n < 10 = [n]
| otherwise = (mod n 10) : (digits (div n 10))
*ghci> digits 1234 = [3,1,2,4]*
digits' :: Int -> [Int]
digits' n = (x)
where x
| n < 10 = [n]
| otherwise = (mod n 10) : (digits' (div n 10))
*ghci>digits' 1234 = [4,3,2,1]*
根据我的理解,数字的评估1234
应为[1,2,3,4]
。但是看来我缺少一些东西。谁能解释一下?
digits :: Int -> [Int]
digits n = reverse (x)
where x
| n < 10 = [n]
| otherwise = (mod n 10) : (digits (div n 10))
*ghci> digits 1234 = [3,1,2,4]*
digits' :: Int -> [Int]
digits' n = (x)
where x
| n < 10 = [n]
| otherwise = (mod n 10) : (digits' (div n 10))
*ghci>digits' 1234 = [4,3,2,1]*
As per my understanding the evaluation of digits 1234
should be [1,2,3,4]
. But it seems that I am missing something. Can anyone explain this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于
Digits
逆转每个递归调用中的字符串,而不仅仅是在外部级别。尝试digits x =反向(Digits'X)
(或等效地,digits = reverse。reverse。digits'
),看看您是否可以解释差异。The problem is that
digits
reverses the string in each recursive call, not just once at the outer level. Trydigits x = reverse (digits' x)
(or, equivalently,digits = reverse . digits'
), and see if you can explain the difference.尽管有Amalloy的出色答案,但这里是一种以预期顺序获取数字的方法,而无需涉及
reverse
库函数。我们在此处指出的递归调用的一些额外参数(“ comgulator ”)在这里使用的一些额外参数中使用了累积结果的常见技巧。
我们还使用 库函数,该功能返回包含商和其余部分的对。
累加器通过连续的准备操作,以使数字最终以适当的顺序排列。
Notwithstanding the excellent answer by amalloy, here is a way of getting the digits in the expected order without involving the
reverse
library function.We use the common trick of accumulating the result in some extra argument of the recursive call, (the “accumulator”) noted here as
dgs
.We also use the
divMod
library function, which returns a pair containing both the quotient and the remainder.The accumulator grows by successive prepending operations, in such a way that the digits end up in the appropriate order.