haskell检查用户输入错误 [英] haskell check for user input errors
问题描述
我在haskell中编写应用程序,我想知道这是检查用户输入是否正常的最好方法,例如当Im询问int时是int还是询问格式良好的日期时它的日期?
感谢您的帮助
使用 maybeRead :: Read a => String - >也许 maybeRead
。该函数是Haskell库中包含
的候选对象,但它尚未在
中生效。因此请包括它的代码。这里有一个完整的解决方案:
$ p $ $ b $ import $ Data.Time
import Data.Maybe(listToMaybe )
import System.IO(hSetBuffering,BufferMode(NoBuffering),stdout)
hSetBuffering stdout NoBuffering
putStr输入一个Int:
maybeInt< - fmap maybeRead getLine :: IO(Maybe Int)
maybe(putStrLnThat's not Int!)
(putStrLn。(The Int is ++)。show)
maybeInt
putStr输入日期:
maybeDate< - fmap maybeRead getLine :: IO(也许日)
也许(putStrLn不是日期!)
(putStrLn。(日期是++)。show)
mayDate
maybeRead = fmap fst。 listToMaybe。过滤器(null。snd)。读取
Im writing app in haskell and I would like to know that is the best way to check if users input is ok for example is it int when Im asking for int or if its date when asking for well formed date ?
Thanks for help
Use maybeRead
. That function is a candidate for
inclusion in the Haskell libraries, but it hasn't made it in
yet. So include the code for it. Here's a complete solution:
import Data.Time import Data.Maybe (listToMaybe) import System.IO (hSetBuffering, BufferMode(NoBuffering), stdout)main = do hSetBuffering stdout NoBuffering putStr "Enter an Int: " maybeInt <- fmap maybeRead getLine :: IO (Maybe Int) maybe (putStrLn "That's not an Int!") (putStrLn . ("The Int is " ++) . show) maybeInt putStr "Enter a date: " maybeDate <- fmap maybeRead getLine :: IO (Maybe Day) maybe (putStrLn "That's not a date!") (putStrLn . ("The date is " ++) . show) maybeDate
maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . filter (null . snd) . reads
这篇关于haskell检查用户输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!