haskellrecursionhextype-conversion

Haskell: recursively convert hex string to integer?


For my homework assignment, I need to convert a hexadecimal string to a base-10 integer using a recursive function (with as many helper methods as necessary).

This is what I've got so far:

-- Question 1, part (c):
hexChar :: Char -> Integer
hexChar ch
    | ch == '0' = 0
    | ch == '1' = 1
    | ch == '2' = 2
    | ch == '3' = 3
    | ch == '4' = 4
    | ch == '5' = 5
    | ch == '6' = 6
    | ch == '7' = 7
    | ch == '8' = 8
    | ch == '9' = 9
    | ch == 'A' = 10
    | ch == 'B' = 11
    | ch == 'C' = 12
    | ch == 'D' = 13
    | ch == 'E' = 14
    | ch == 'F' = 15
    | otherwise     = 0

parseHex :: String -> Integer
parseHex hxStr 
    | length hxStr /= 0 = (hexChar(last(hxStr)))+(10*parseHex(init(hxStr)))
    | otherwise         = 0  

However, this does not produce the correct results. Does anyone know of the correct way to do this?


Solution

  • You are really close. your error is on this line:

        | length hxStr /= 0 = (hexChar(last(hxStr)))+(10*parseHex(init(hxStr)))
    

    Think about why you are multiplying by 10. Remember ... Hexadecimal is base 16.