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

标签 haskell recursion binary

我发现这段代码有效,但我不明白为什么会这样。它将 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/

相关文章:

Java按位运算返回 "wrong"值

haskell - 定义泛型实例时触发单态限制

haskell - 记录字段的类型不一致

Groovy 2.1.9 中的闭包递归

java.lang.stackoverflow错误递归

c++ - 表示位在数组中表示的旋转

python - 类型错误 : 'dict' does not Support the Buffer Interface

haskell - 理解 Haskell 中的键值构造函数

haskell - 如何在元组列表中查找重复项?

java - 找到从左上角到右下角的所有路径问题。以数组为参数的递归解法输出说明