我通過教程在https://en.wikibooks.org/wiki/Haskell/Monad_transformers理解MonadTransformer例子
要我寫了下面這段代碼。一個沒有和其他與MonadTransformer
例如:
-- Simple Get Password functions.
getPassphrase1 :: IO (Maybe String)
getPassphrase1 = do
password <- getLine
if isValid password
then return $ Just password
else return Nothing
askPassphrase1 :: IO()
askPassphrase1 = do
putStrLn "Enter password < 8 , alpha, number and punctuation:"
p <- getPassphrase1
case p of
Nothing -> do -- Q1. ### How to implement this with `MonadTrans` ?
putStrLn "Invalid password. Enter again:"
askPassphrase1
Just password ->
putStrLn $ "Your password is " ++ password
-- The validation test could be anything we want it to be.
isValid :: String -> Bool
isValid s = length s >= 8
&& any isAlpha s
&& any isNumber s
&& any isPunctuation s
另一個使用MonadT
我寫我自己。
getPassphrase2 :: MaybeT IO String
getPassphrase2 = do
password <- lift getLine
guard $ isValid password
return password
askPassphrase2 :: MaybeT IO()
askPassphrase2 = do
lift $ putStrLn "Enter password < 8 , alpha, number and punctuation:"
p <- getPassphrase2
-- Q1. How to print "Invalid password" ?
lift $ putStrLn $ "Your password is " ++ p
-- The validation test could be anything we want it to be.
isValid :: String -> Bool
isValid s = length s >= 8
&& any isAlpha s
&& any isNumber s
&& any isPunctuation s
main :: IO()
main = do
a <- runMaybeT askPassphrase2
return()
這兩個作品。
但我無法理解如何在MonadTrans
示例中添加wrong password
支持。 ?
另外,是main
方法好嗎..或者它可以寫得更好?
如果您不打算使用它,則無需將值綁定到'a'; 'main = runMaybeT askPassphrase >> return()' – chepner