我发现这段代码有效,但我不明白为什么会这样。它将 Int 转换为其二进制表示。
repBinario::Int -> Int
repBinario 0 = 0
repBinario x = 10 * repBinario (x `div` 2) + x `mod` 2
我知道
div
和 mod
做。但是,它如何放置来自 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/