如何在 Haskell getLine 中只允许一种类型

How to allow only one type in Haskell getLine

我有这段代码可以将一个人添加到我的 txt。但是在名称中,例如,我只想允许字母。除了年龄,我只想让数字

add = do
    putStrLn "Name:"
    name <- getLine
    putStrLn "Age:"
    age <- getLine
    let new =  (name ++ " "++ idade ++ "\n")
    appendFile "funcionarios.txt" new
    putStrLn "Success!"

来自 Read class 来源:

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