Home > Net >  How can I manage to print from a monad transformer
How can I manage to print from a monad transformer

Time:04-30

I managed to get compiling code for the monad transformer MaybeT. (I was following the haskell wikibook)

However, I dont seem to manage to make my code print anything

running askPassphrase on ghci, I get a noinstance error: No instance for (Data.Functor.Classes.Show1 IO) arising from a use of ‘print’

I dont even know how to read the error! A no instance of Show would have made much more sense to me.

What I tryed so far: basically hitting my head against the wall. I dont even know what to try. Perhaps I could write a specialized version of print for MaybeT IO String, but that seems to defeat the purpose...

Something like

p :: Show a => MaybeT IO a -> IO ()
p maybeIO= do a' <- runMaybeT maybeIO
              print a'

Works, but seems wrong... Can't I get it to print from inside MaybeT IO ?

The MaybeT IO String code follows

import Control.Monad
import Control.Applicative
import Control.Monad.Trans
import Control.Monad.Trans.Maybe


    
isValid :: String -> Bool
isValid s = length s >= 8

getPassphrase :: MaybeT IO String
getPassphrase = do s <- lift getLine
                   guard (isValid s)
                   return s

askPassphrase :: MaybeT IO ()
askPassphrase = do lift $ putStrLn "Insert your new passphrase:"
                   value <- getPassphrase
                   lift $ putStrLn "Storing in database..."

CodePudding user response:

Use runMaybeT:

> runMaybeT askPassphrase
Insert your new passphrase:
asdf
Nothing
> runMaybeT askPassphrase
Insert your new passphrase:
asdfghjk
Storing in database...
Just ()
  • Related