Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Couldn't match expected type 'String' with actual type 'Char'

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)

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'
like image 648
john stamos Avatar asked Dec 26 '22 09:12

john stamos


1 Answers

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").

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]

This is typically written inline, as (:[]), equivalent to \x -> (x : []) or \x -> [x].

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 = ...
  ...

You can convert that to a less repetitious, more efficient equivalent with case:

f x = case x of
  A -> ...
  B -> ...
  C -> ...
  ...
like image 56
Jon Purdy Avatar answered Apr 19 '23 23:04

Jon Purdy