haskell - 需要整数的字符串

时间:2014-11-27 16:17:31

标签: string haskell error-handling functional-programming

我有以下代码

data Ops = Sum Integer | Div Integer | None deriving (Read)

main = do
    ans <- getLine
print $ case read ans of
    Sum n -> sum n
    Div n -> div n

我想向用户显示错误信息

Nothing -> "Error"

我知道我不能在这里插入一个字符串,所以我怎么可能实现错误条件

2 个答案:

答案 0 :(得分:4)

更好的选择是使用readMaybe中的Text.Read

import Text.Read (readMaybe)

data Ops
    = Sum Integer
    | Div Integer
    | None
    deriving (Eq, Show, Read)

main :: IO ()
main = do
    ans <- getLine
    case readMaybe ans of
        Nothing -> putStrLn "Error"
        Just x  -> print $ handleInput x
    where
        handleInput (Sum n) = sum n
        handleInput (Div n) = div n

这使您可以将错误处理与处理输入的方式分开,将其转移到远离IO

的纯函数中

答案 1 :(得分:0)

如果您无法使用Text.Read这样的模块,那么如何根据前奏函数定义readMaybe

data Foo = Sum Int Int | Div Int Int deriving (Show,Read)

readMaybe str =
  case reads str of
    [] -> Nothing
    ((a,_):_) -> Just a

main = do
  str <- getLine
  case readMaybe str of
    Nothing         -> putStrLn "bad input"
    Just (Sum a b)  -> print $ a + b
    Just (Div a b)  -> print $ div a b