Haskell函数使用show和return Integer

时间:2017-11-15 18:06:58

标签: haskell io show

我正在对此进行故障排除很长时间。

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

这应该将String转换为Integer,但是如果它找不到Number字符,它将打印“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 function解决问题。

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

show不会打印任何内容。它只是将某些内容转换为String

的函数

my_digit应该是Int| otherwise = show ("Not a Number: '" ++ [y] ++ "'")会返回一个字符串。您是否可以使用error代替show

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

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