2017-08-03 46 views
0

我对Haskell很新,我试图做一个简单的密码程序作为我的第一个程序。我遇到了一个问题,我不确定如何解决它。我不知道如何制作密码的第二部分。Haskell密码程序

main = do 
    putStrLn "Hello, Who are you?" 
    name <- getLine --User Input 
    putStrLn ("Hey " ++ name ++ ", What's the password?") 
    pass <- getLine 
    if pass == "12345" 
     then do 
     putStrLn ("Welcome") 
     pw -- Go to password Prompt 
     else do 
      putStrLn "That is wrong!" 
      main --Sent back to beginning 
pw = do 
putStrLn "What Password do you need?" 

我不知道如何切换到询问需要哪个密码,我非常确定我知道如何列出它们。目标是要求用户输入哪个密码,如雅虎等网站列表,然后用户选择一个密码。在此先感谢:d

+0

说明的目标不是很清楚。你是否需要额外的提示选择一个网站,然后要求输入一个密码,该密码是基于之前选择的网站进行验证的?如果是这样,你可能想要一个像[[(String,String)]这样的代表网站与密码关联的东西(不管是什么,因为字符串不是好的做法)。最后,如果您尝试过失败,请将问题包括在内。 – user2407038

+0

提示我的意思是如果用户正确输入第一个密码,则要求用户从集列表中选择。不是一个全新的提示。为网站制作一些有关密码的数据库。你可能对许多字符串是正确的。我对编程场景颇为陌生。我道歉。还有一个'[(String,String)]'例如我会用[[(Yahoo,12345)]'?如果是的话,我将如何呼吁呢? – Casey

+0

我已经解决了拔出“你需要什么密码?”的问题。通过在'then'之后加上'do',但问题仍然在于提出网站列表并能够键入网站并将网站用户的密码告知。 – Casey

回答

2

如果我理解正确的话,你想创造的东西,看起来像这样:

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是因为它能够找到Yahoowebsites。现在我们只需要一点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 :("