【发布时间】:2021-03-28 02:55:22
【问题描述】:
我正在学习 Haskell 和递归,Haskell 中的不同类型让我很头疼。我正在尝试创建一个递归函数,它将采用 32 位二进制数字符串并将其转换为十进制数。我认为我对递归如何工作的想法很好,但是在 Haskell 中实现它让我头疼。这是我目前所拥有的:
bin2dec :: String -> Int
bin2dec xs = ""
bin2dec (x:xs) = bin2dec xs + 2^(length xs) * x
该函数应该取一个 32 位数字字符串,然后取出字符串的第一个字符。例如,“0100101010100101”变为“0”和“100101010100101”。然后它应该将第一个字符转换为整数并将其乘以字符串其余部分的 2^length 并再次将其添加到函数调用中。所以如果 32 位字符串中的第一个字符是“1”,那么它就变成了 1 * 2^(31) + 递归函数调用。
但是,每当我尝试编译它时,它都会返回:
traceProcP1.hs:47:14: error:
* Couldn't match type `[Char]' with `Int'
Expected: Int
Actual: String
* In the expression: ""
In an equation for `bin2dec': bin2dec xs = ""
|
47 | bin2dec xs = ""
| ^^
traceProcP1.hs:48:31: error:
* Couldn't match expected type `Int' with actual type `Char'
* In the second argument of `(+)', namely `2 ^ (length xs) * x'
In the expression: bin2dec xs + 2 ^ (length xs) * x
In an equation for `bin2dec':
bin2dec (x : xs) = bin2dec xs + 2 ^ (length xs) * x
|
48 | bin2dec (x:xs) = bin2dec xs + 2^(length xs) * x
| ^^^^^^^^^^^^^^^^^^
我知道这与更改数据类型有关,但我在 Haskell 中进行类型转换时遇到问题。我尝试使用 read 输入 x 并且我尝试制作将“0”变成 0 和“1”变成 1 的保护,但我无法让这些工作。任何帮助将不胜感激。
【问题讨论】:
-
除了打字问题外,值得指出的是您的模式顺序错误。匹配是自上而下的,并在第一个匹配处停止 - 所以一旦修复它以便编译,任何字符串都会得到 0。您需要切换顺序或更改模式,以便它不会捕获所有内容,而只会捕获空字符串。
标签: function haskell recursion casting type-conversion