Haskell中的反向功能行为

发布于 2025-02-03 12:59:56 字数 703 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

荒人说梦 2025-02-10 12:59:56

问题在于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. Try digits x = reverse (digits' x) (or, equivalently, digits = reverse . digits'), and see if you can explain the difference.

只是一片海 2025-02-10 12:59:56

尽管有Amalloy的出色答案,但这里是一种以预期顺序获取数字的方法,而无需涉及reverse库函数。

我们在此处指出的递归调用的一些额外参数(“ comgulator ”)在这里使用的一些额外参数中使用了累积结果的常见技巧。

我们还使用 库函数,该功能返回包含商和其余部分的对。

digits :: Int -> [Int]
digits n = go [] n
  where
    base      =  10
    go dgs k  =  if (k < base)  then  (k:dgs)
                                else  let  (q,r) = divMod k base
                                      in   go (r:dgs) q

累加器通过连续的准备操作,以使数字最终以适当的顺序排列。

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.

digits :: Int -> [Int]
digits n = go [] n
  where
    base      =  10
    go dgs k  =  if (k < base)  then  (k:dgs)
                                else  let  (q,r) = divMod k base
                                      in   go (r:dgs) q

The accumulator grows by successive prepending operations, in such a way that the digits end up in the appropriate order.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文