繁体   English   中英

haskell-需要整数的字符串

[英]haskell - String where integer is needed

我有以下代码

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"

我知道我不能在此处插入字符串,因此如何实现错误条件

更好的选择是使用readMaybeText.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中拉出成为纯函数

如果您不能使用像Text.Read这样的模块,请Text.Read此处,如何仅通过Prelude函数定义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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM