【问题标题】:Haskell function use show and return IntegerHaskell 函数使用 show 并返回 Integer
【发布时间】: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 ,因此其调用者无法处理错误。重写 解决此问题的功能"

感谢您的帮助。

【问题讨论】:

    标签: haskell io show


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答。我想打印出来输出。例如使用 print 或 putStrLn。
    • @lukaskiss 我的解决方案(使用错误)对你有用吗,还是你在寻找别的东西?
    • 是的,它可以工作:) 但我正在尝试解决这个练习:“函数使用错误,所以它的调用者无法处理错误。重写函数来解决这个问题”
    • @lukaskiss 您不能在纯函数中打印出东西,您必须将其设为 IO 函数,使用 unsafePerformIO 之类的不安全方式,或者使用 writer monad 之类的东西懒惰地将结果打印为他们执行。一般来说,最好的方法是将其保留为纯函数并返回您需要打印的结果
    • @lukaskiss 在成为 Haskell 专家之前,切勿使用 unsafePerformIO。假装它不存在——它被称为不安全是有原因的。如果您真的必须在该函数中打印,请阅读 IO monad 以及如何使用它。我认为最好不打印任何内容,并保持函数纯净。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多