String haskell-需要整数的字符串
我有以下代码String haskell-需要整数的字符串,string,haskell,error-handling,functional-programming,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 我知道我不能在这里插入字符串,因此如何实现错误条件更好的选择是使用readMaybe from Text。阅读: 这使您可以将错误处理与处理输入的方式分开,将其
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
我知道我不能在这里插入字符串,因此如何实现错误条件更好的选择是使用readMaybe from Text。阅读:
这使您可以将错误处理与处理输入的方式分开,将其提取到一个纯函数中,远离IO更好的选择是使用readMaybe from Text。阅读:
这使您可以将错误处理与处理输入的方式分开,如果无法使用类似于模块的文本,则将错误处理与输入分离成一个纯函数。这里阅读的是如何定义readMaybe,仅从Prelude函数的角度:
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
如果您不能使用像文本这样的模块,请阅读这里的内容,了解如何定义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
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