本文介绍了Haskell:递归转换十六进制字符串为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于我的家庭作业,我需要使用递归函数将十六进制字符串转换为基数为10的整数(必要时使用许多助手方法)。
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?
推荐答案
你真的很接近。你的错误在这一行:
You are really close. your error is on this line:
| length hxStr /= 0 = (hexChar(last(hxStr)))+(10*parseHex(init(hxStr)))
想想为什么你乘以10.记住......十六进制是16位。
Think about why you are multiplying by 10. Remember ... Hexadecimal is base 16.
这篇关于Haskell:递归转换十六进制字符串为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!