Haskell 无法将预期类型“字符串"与实际类型“字符"匹配 [英] Haskell Couldn't match expected type 'String' with actual type 'Char'
问题描述
我想知道为什么会出现此错误.这是一个分配,我要将整数从整数转换为十六进制值.当我通过 16
修改整数值时,我调用了这个辅助转换函数.(与整数值连接,然后在递归调用中除以 16
)
I am wondering why I'm getting this error. It's for an assignment where i'm to convert from an integer to a hex value. I call this helper conversion function when I mod the integer value by 16
. (concatenated with the integer value which I then divide by 16
in a recursive call)
这是我的代码:
changeToHex :: Integer -> String
--main function
toHex :: Integer -> String
toHex x
|x == 0 = '0'
|x == 1 = '1'
|x == 2 = '2'
|x == 3 = '3'
|x == 4 = '4'
|x == 5 = '5'
|x == 6 = '6'
|x == 7 = '7'
|x == 8 = '8'
|x == 9 = '9'
|x == 10 = 'A'
|x == 11 = 'B'
|x == 12 = 'C'
|x == 13 = 'D'
|x == 14 = 'E'
|x == 15 = 'F'
推荐答案
使用单引号 ('F'
) 为您提供 Char
文字.对于 String
文字,实际上是 Char
值的列表,您应该使用双引号 ("F"
).
Using single quotes ('F'
) gives you a Char
literal. For a String
literal, which is in fact a list of Char
values, you should use double quotes ("F"
).
由于 String
是 [Char]
的别名,如果您想从 Char
转换为 String
,您可以仅将 Char
包装在一个元素列表中.这样做的函数可能如下所示:
Since String
is an alias for [Char]
, if you want to convert from a Char
to a String
, you can merely wrap the Char
in a one-element list. A function to do so might look like:
stringFromChar :: Char -> String
stringFromChar x = [x]
这通常是内联编写的,如 (:[])
,相当于 x ->;(x : [])
或 x ->[x]
.
This is typically written inline, as (:[])
, equivalent to x -> (x : [])
or x -> [x]
.
顺便说一句,您可以大大简化您的代码,例如使用 Enum
类型类:
As an aside, you can simplify your code considerably, using for example the Enum
typeclass:
toHexDigit :: Int -> Char
toHexDigit x
| x < 0 = error "toHex: negative digit value"
| x < 10 = toEnum $ fromEnum '0' + x
| x < 15 = toEnum $ fromEnum 'A' + x - 10
| otherwise = error "toHex: digit value too large"
更一般地说,任何时候你都有这样的功能:
More generally, any time you have a function like:
f x
| x == A = ...
| x == B = ...
| x == C = ...
...
您可以使用 case
将其转换为更少重复、更高效的等价物:
You can convert that to a less repetitious, more efficient equivalent with case
:
f x = case x of
A -> ...
B -> ...
C -> ...
...
这篇关于Haskell 无法将预期类型“字符串"与实际类型“字符"匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!