haskell检查用户输入错误 [英] haskell check for user input errors

查看:125
本文介绍了haskell检查用户输入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在haskell中编写应用程序,我想知道这是检查用户输入是否正常的最好方法,例如当Im询问int时是int还是询问格式良好的日期时它的日期?



感谢您的帮助

解决方案

使用 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 :: Read a => String - >也许
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆