在 Haskell 中混合 Monad
我正在尝试在 haskell 中使用 Ubigraph,但我相信我的问题更通用。我正在尝试编译:
import Graphics.Ubigraph
import Control.Monad
import System.Posix.Unistd
main = do
h <- initHubigraph "http://127.0.0.1:20738/RPC2"
runHubigraph op h
op = do
clear
vs <- mapM (const newVertex) [0..200]
mapM_ (setVAttr (VShape Sphere)) vs
putStrLn "something"
let bind i = zipWithM (\a b -> newEdge (a,b)) vs (drop i vs ++ take i vs)
mapM_ bind [1..15]
mapM_ (removeVertex) vs
return ()
并且我得到了
无法匹配预期类型`Control.Monad.Trans.Reader.ReaderT Ubigraph IO a0' 与实际类型“IO ()” 在“putStrLn”调用的返回类型中 在 'do' 表达式的 stmt 中: putStrLn "something" 在表达式中: 做{清除; vs <-mapM (const newVertex) [0 .. 200]; mapM_(setVAttr(VShape Sphere)) vs; putStrLn“某事”; ....}
我可以看到 op 的类型如何隐含为与 putStrLn 的返回类型不同的东西,但我不确定如何重新设计此代码以正确编译。我可以简单地更改 op 函数的返回类型吗?
谢谢
I'm trying to work with Ubigraph in haskell, but I believe my problem is more generic. I'm trying to compile:
import Graphics.Ubigraph
import Control.Monad
import System.Posix.Unistd
main = do
h <- initHubigraph "http://127.0.0.1:20738/RPC2"
runHubigraph op h
op = do
clear
vs <- mapM (const newVertex) [0..200]
mapM_ (setVAttr (VShape Sphere)) vs
putStrLn "something"
let bind i = zipWithM (\a b -> newEdge (a,b)) vs (drop i vs ++ take i vs)
mapM_ bind [1..15]
mapM_ (removeVertex) vs
return ()
and I am getting
Couldn't match expected type `Control.Monad.Trans.Reader.ReaderT Ubigraph IO a0' with actual type `IO ()' In the return type of a call of `putStrLn' In a stmt of a 'do' expression: putStrLn "something" In the expression: do { clear; vs <- mapM (const newVertex) [0 .. 200]; mapM_ (setVAttr (VShape Sphere)) vs; putStrLn "something"; .... }
I can see how the type of op is being implied as something different from the return type of putStrLn, but I am not sure how I would reengineer this code to compile properly. Can I simply change the return type of the op function?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您对埋藏在
op
中的putStrLn
的调用位于IO
monad 中。您需要将其提升到 Ubigraph monad 中,使用这样的提升函数可以帮助您访问堆栈中较低的 Monadic 函数。在这种情况下,
Ubigraph
是一个由IO monad组成的Reader monad,IO monad位于底部。所以IO里面的东西一定要解除。liftIO
来自MonadIO
类,在变压器包中。Your call to
putStrLn
buried down inop
is in theIO
monad. You will need to lift it into theUbigraph
monad, usingSuch lifting functions help you access monadic functions lower in the stack. In this case,
Ubigraph
is a Reader monad composed with the IO monad, and the IO monad is at the bottom. So things in IO must be lifted.liftIO
is from theMonadIO
class, in the transformers package.