haskell - Haskell 中的反向函数行为

标签 haskell where-clause reverse ghci

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]*

根据我的理解,digits 1234 的计算应该是 [1,2,3,4]。但似乎我错过了什么。谁能解释一下?

最佳答案

问题是 digits 在每次递归调用中都会反转字符串,而不仅仅是在外层一次。试试 digits x = reverse (digits' x)(或者,等价地,digits = reverse .digits'),看看你能否解释其中的区别。

关于haskell - Haskell 中的反向函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72441692/

相关文章:

string - 从 Haskell 中的字符串替换子字符串

带 head 函数的 Haskell 惰性问题

python - Numpy np.where 多重条件

选择排名查询后的 MySql Where 条件

c - 反转字符串功能无法正常工作

haskell - 是什么导致了 "irrefutable pattern failed for pattern",它是什么意思?

haskell - 为镜头寻找缺失的状态组合器

sql - 在 DB2 中使用指定本周获取记录的 where 条件获取记录

c - 反转字符串(输入参数并返回字符串)

C++ - 尝试使用字符串函数来反转输入字符串