如果我理解正确的话,你想创造的东西,看起来像这样:
What password do you need?
用户输入Yahoo
OK, the password for the website "Yahoo" is "asdf"
要做到这一点,你会需要一组网站及其相关的密码。您可以将网站和密码表示为String
s。关联列表(这是你需要的)最好的一种收集是Map
。因此,在您的模块的顶部,进口Data.Map.Strict
:
import qualified Data.Map.Strict as Map
现在,您可以访问记录here的所有类型和功能。现在,你可以使用Map.fromList :: [(String,String)] -> Map.Map String String
(从String
个映射到其他String
S)转[(String,String)]
(一对String
列表)为Map.Map String String
:
websites :: Map.Map String String
websites = Map.fromList
[("Yahoo","asdf")
,("Google","meow")
-- You can add more here if you need to
]
现在,你可以使用Map.lookup :: String -> Map.Map String String -> Maybe String
查找一个网站并获取其相关密码:
Map.lookup "Yahoo" websites ==> Just "asdf"
注意它返回Just "asdf"
,而不是Nothing
是因为它能够找到Yahoo
在websites
。现在我们只需要一点IO胶水来获得用户的输入并打印出结果,如下所示:
-- Get the website name and put it in websiteName
putStrLn "What password do you need?"
websiteName <- getLine
-- Check our Map for the website name the user gave us
case Map.lookup websiteName websites of
-- If we found the password, print it out with a nice message
Just thePassword -> putStrLn $ "OK, your password is: " ++ thePassword
-- If that website was not in our Map, print an error message
Nothing -> putStrLn "Website not found :("
说明的目标不是很清楚。你是否需要额外的提示选择一个网站,然后要求输入一个密码,该密码是基于之前选择的网站进行验证的?如果是这样,你可能想要一个像[[(String,String)]这样的代表网站与密码关联的东西(不管是什么,因为字符串不是好的做法)。最后,如果您尝试过失败,请将问题包括在内。 – user2407038
提示我的意思是如果用户正确输入第一个密码,则要求用户从集列表中选择。不是一个全新的提示。为网站制作一些有关密码的数据库。你可能对许多字符串是正确的。我对编程场景颇为陌生。我道歉。还有一个'[(String,String)]'例如我会用[[(Yahoo,12345)]'?如果是的话,我将如何呼吁呢? – Casey
我已经解决了拔出“你需要什么密码?”的问题。通过在'then'之后加上'do',但问题仍然在于提出网站列表并能够键入网站并将网站用户的密码告知。 – Casey