【发布时间】:2017-11-15 18:06:57
【问题描述】:
我正在解决这个问题很长时间。
asInt_either2 :: String -> Int
asInt_either2 str
| null str = 0
| (head str) == '-' = -1 * asInt_either2 (tail str)
| isNumber (head str) = foldl' nasob 0 str
| otherwise = error ("Not a Number: '" ++ [(head str)] ++ "'")
where nasob x y = x*10 + (my_digit y)
my_digit y
| isNumber y = digitToInt y
| otherwise = show ("Not a Number: '" ++ [y] ++ "'")
这只是应该将字符串转换为整数,但如果它发现不是数字字符,它将打印“不是数字:'a'”(例如)
我试图让它工作,但我仍然得到错误。 我知道,有更好的解决方案,但这对我来说是练习,如果可能的话,我想尝试这种方式。
我收到错误:
• Couldn't match type ‘[Char]’ with ‘Int’
Expected type: Int
Actual type: String
• In the expression: show ("Not a Number: '" ++ [y] ++ "'")
In an equation for ‘my_digit’:
my_digit y
| isNumber y = digitToInt y
| otherwise = show ("Not a Number: '" ++ [y] ++ "'")
In an equation for ‘asInt_either2’:
asInt_either2 str
| null str = 0
| (head str) == '-' = - 1 * asInt_either2 (tail str)
| isNumber (head str) = foldl' nasob 0 str
| otherwise = error ("Not a Number: '" ++ [(head str)] ++ "'")
where
nasob x y = x * 10 + (my_digit y)
my_digit y
| isNumber y = digitToInt y
| otherwise = show ("Not a Number: '" ++ [y] ++ "'")
更新:
改写show到error函数解决问题。
但我正在尝试解决这个问题: “该函数使用 error ,因此其调用者无法处理错误。重写 解决此问题的功能"
感谢您的帮助。
【问题讨论】: