2017-08-03 37 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 :("