haskell - understanding MonadTransformer examples -
i going through tutorial @ https://en.wikibooks.org/wiki/haskell/monad_transformers
i wrote following piece of codes. 1 without , other monadtransformer
instance :
-- simple password functions. getpassphrase1 :: io (maybe string) getpassphrase1 = password <- getline if isvalid password return $ password else return nothing askpassphrase1 :: io () askpassphrase1 = putstrln "enter password < 8 , alpha, number , punctuation:" p <- getpassphrase1 case p of nothing -> -- q1. ### how implement `monadtrans` ? putstrln "invalid password. enter again:" askpassphrase1 password -> putstrln $ "your password " ++ password -- validation test want be. isvalid :: string -> bool isvalid s = length s >= 8 && isalpha s && isnumber s && ispunctuation s
another using monadt
wrote myself.
getpassphrase2 :: maybet io string getpassphrase2 = password <- lift getline guard $ isvalid password return password askpassphrase2 :: maybet io () askpassphrase2 = lift $ putstrln "enter password < 8 , alpha, number , punctuation:" p <- getpassphrase2 -- q1. how print "invalid password" ? lift $ putstrln $ "your password " ++ p -- validation test want be. isvalid :: string -> bool isvalid s = length s >= 8 && isalpha s && isnumber s && ispunctuation s main :: io () main = <- runmaybet askpassphrase2 return ()
both works.
but unable understand how add wrong password
support in monadtrans
example. ?
also, main
method ok.. or can written in better way ?
guard
not want in maybet approach. check invalid password and able provide own processing in case use original version of getpassphase
, lift the maybet io
monad:
getpassphease2 = result <- lift $ getpassphrase1 case result of nothing -> lift $ putstrln "bad password" pw -> lift $ putstrln "your password is: " ++ pw
explanation...
the maybet io
monad giving io-actions capability fail and having failure automatically handled monad. if step fails, control goes way runmaybet
, runmaybet
returns nothing
. it's throwing exception.
the point of using maybet
no have explicitly check see if step has failed - checking performed maybet
monad after each step called. means can write code assuming each preceding step has succeeded - i.e. if on "happy path". means can't different if previous step failed.
one possibility using maybet
version of getpassphrase
this:
main = result <- runmaybet askpassphrase2 case result of _ -> return () nothing -> putstrln "some failure happened... perhaps wrong password?"
the problem if runmaybet
returns nothing
mean step in askpassphrase
failed, not guard
.
another way use maybet version of getpassphrase
have askpassphrase
run runmaybet
:
askpassphrase2 = result <- lift $ runmaybet getpassphrase2 case result of nothing -> lift $ putstrln "bad password" pw -> lift $ putstrln $ "your password " ++ pw
here we're using runmaybet
try-catch block.
Comments
Post a Comment