Haskell Could not match expected type 'String' to actual type 'Char'
I am wondering why I am getting this error. This is for the destination where I have to convert from integer to hex. I call this helper conversion function when I change the integer value to 16
. (combined with an integer value, which I then divide by 16
on a recursive call)
Here is my code:
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'
source to share
Using single quotes ( 'F'
) gives you a literal Char
. For a literal String
that is actually a list of values Char
, you must use double quotes ( "F"
).
Since String
is an alias for [Char]
, if you want to convert from Char
to String
, you can simply wrap Char
in a singleton list. The function for this might look like this:
stringFromChar :: Char -> String
stringFromChar x = [x]
This is usually written on a line like (:[])
, equivalent to \x -> (x : [])
or \x -> [x]
.
As an aside, you can greatly simplify your code by using, for example, 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, every time you have a function like:
f x
| x == A = ...
| x == B = ...
| x == C = ...
...
You can convert this to a less repetitive, more efficient equivalent with case
:
f x = case x of
A -> ...
B -> ...
C -> ...
...
source to share