Haskell 函数使用 show 和 return Integer

Haskell function use show and return Integer

我已经解决这个问题很长时间了。

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] ++ "'")

这应该简单地将字符串转换为整数,但如果它发现不是数字字符,它将打印 "Not a Number : '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 to error函数解决问题。

但我正在尝试解决此练习: “该函数使用错误,因此它的调用者无法处理错误。重写 解决这个问题的功能

感谢您的帮助。

show 不打印任何内容。它只是一个将某些东西转换成 String

的函数

my_digit 应该是一个 Int| otherwise = show ("Not a Number: '" ++ [y] ++ "'") returns 是一个字符串。您可能是想使用 error 而不是 show 吗?

        my_digit y                 
          | isNumber y = digitToInt y                                          
          | otherwise = error ("Not a Number: '" ++ [y] ++ "'")

这将导致程序在遇到非数字字符时失败并打印您的错误消息。