gpt4 book ai didi

haskell - 在 Haskell 中将十进制转换为二进制

转载 作者:行者123 更新时间:2023-12-04 10:03:16 25 4
gpt4 key购买 nike

我发现这段代码有效,但我不明白为什么会这样。它将 Int 转换为其二进制表示。

repBinario::Int -> Int
repBinario 0 = 0
repBinario x = 10 * repBinario (x `div` 2) + x `mod` 2

我知道 divmod做。但是,它如何放置来自 mod 的每个数字?一起?

最佳答案

简而言之,它将累积结果乘以 10在每次迭代中。

为了更清楚地了解正在发生的事情,我们可以将您的函数分为两个更简单的函数。第一个将整数转换为二进制数字列表。然后另一个会做让你烦恼的事情:将二进制数字列表连接成一个整数。

extractBinDigits :: Int -> [Int]
extractBinDigits =
unfoldr (\x -> if x == 0 then Nothing else Just (mod x 2, div x 2))

concatDigits :: [Int] -> Int
concatDigits =
foldr (\a b -> a + b * 10) 0

如您所见,我们只是将列表折叠起来,将累加器乘以 10。在每个步骤上并添加每个数字。

然后你的原始功能就变成了这样:
repBinario :: Int -> Int
repBinario =
concatDigits . extractBinDigits

Division 现在允许我们检查和重用程序中更精细的部分,从而为我们提供更大的灵 active 。例如,通过添加另一个简单的函数,您现在可以一次将整数转换为字符串:
showDigits :: [Int] -> String
showDigits =
reverse . map (chr . (+ 48))

repStringyBinario :: Int -> String
repStringyBinario =
showDigits . extractBinDigits

关于haskell - 在 Haskell 中将十进制转换为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com