如果我理解正確的話,你想創造的東西,看起來像這樣:
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