我如何设法从 monad 转换器打印
How can I manage to print from a monad transformer
我设法获得了 monad 转换器 MaybeT 的编译代码。
(我正在关注 the haskell wikibook)
但是,我似乎无法让我的代码打印任何东西
运行 askPassphrase
在 ghci 上,我得到一个非实例错误:No instance for (Data.Functor.Classes.Show1 IO) arising from a use of ‘print’
我什至不知道如何阅读错误! no instance of Show
对我来说更有意义。
到目前为止我尝试了什么:基本上是用头撞墙。我什至不知道该尝试什么。也许我可以为 MaybeT IO String
编写专门版本的打印,但这似乎违背了目的...
类似
p :: Show a => MaybeT IO a -> IO ()
p maybeIO= do a' <- runMaybeT maybeIO
print a'
有效,但似乎不对...我不能让它从内部打印 MaybeT IO
吗?
MaybeT IO 字符串代码如下
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..."
使用runMaybeT
:
> runMaybeT askPassphrase
Insert your new passphrase:
asdf
Nothing
> runMaybeT askPassphrase
Insert your new passphrase:
asdfghjk
Storing in database...
Just ()
我设法获得了 monad 转换器 MaybeT 的编译代码。 (我正在关注 the haskell wikibook)
但是,我似乎无法让我的代码打印任何东西
运行 askPassphrase
在 ghci 上,我得到一个非实例错误:No instance for (Data.Functor.Classes.Show1 IO) arising from a use of ‘print’
我什至不知道如何阅读错误! no instance of Show
对我来说更有意义。
到目前为止我尝试了什么:基本上是用头撞墙。我什至不知道该尝试什么。也许我可以为 MaybeT IO String
编写专门版本的打印,但这似乎违背了目的...
类似
p :: Show a => MaybeT IO a -> IO ()
p maybeIO= do a' <- runMaybeT maybeIO
print a'
有效,但似乎不对...我不能让它从内部打印 MaybeT IO
吗?
MaybeT IO 字符串代码如下
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..."
使用runMaybeT
:
> runMaybeT askPassphrase
Insert your new passphrase:
asdf
Nothing
> runMaybeT askPassphrase
Insert your new passphrase:
asdfghjk
Storing in database...
Just ()