我了解(有点)单子并了解运算符 <- 将从单子中提取值。
但它如何与不同的类型一起工作?
通常,我看到它被用来从 IO monad 中提取字符串。但是在下面的示例代码中,我看不到为什么它在主第 3 行失败,抱怨它期待一种 IO int?编译器如何推断需要 IO int?
<-
它 ( ) 在方法中还有什么作用multWithLog
?
import Control.Monad.Trans.Writer.Lazy
main = do
putStrLn $ show $ logNumber 3 -- prints WriterT (Identity (3,["Got Number: 3"]))
putStrLn $ show $ multWithLog -- prints WriterT (Identity (3,["Got Number: 3"]))
_ <- logNumber 3 -- fails with Couldn't match type ‘WriterT [String] Data.Functor.Identity.Identity’ with ‘IO’
-- Expected type: IO Int
-- Actual type: Writer [String] Int
putStrLn "test"
logNumber :: Int -> Writer [String] Int
logNumber x = writer (x, ["Got Number: " ++ show x])
multWithLog :: Writer [String] Int
multWithLog = do
a <- logNumber 3
--b <- logNumber 5
return a