我有这个代码,可以在我的txt中添加一个人。但在名称中,例如,我想只允许字母。和年龄一样,我只想允许数字
add = do
putStrLn "Name:"
name <- getLine
putStrLn "Age:"
age <- getLine
let new = (name ++ " "++ idade ++ "\n")
appendFile "funcionarios.txt" new
putStrLn "Success!"
答案 0 :(得分:5)
来自Read
班级来源:
class Read a where
readsPrec :: Int -> ReadS a
-- (...)
这个ReadS
是什么?来自hoogle:
type ReadS a = String -> [(a, String)]
这允许我们编写可能失败的读取:
maybeRead :: Read a => String -> Maybe a
maybeRead str = case readsPrec 0 str of
[(a, "")] -> Just a
-- ^ ^---- no remaining input string
-- |- output
_ -> Nothing
然后是修改IO的简单案例。这是一个快速肮脏的例子:
main = do
putStrLn "Enter an integer:"
let loop = do
str <- getLine
maybe loop return (maybeRead str :: Maybe Int)
num <- loop
print $ num + 1