我已将以下重写规则添加到管道而没有问题:
{-# RULES "ConduitM: lift x >>= f" forall m f.
lift m >>= f = ConduitM (PipeM (liftM (unConduitM . f) m))
#-}
我正在尝试为liftIO
添加类似的重写规则
{-# RULES "ConduitM: liftIO x >>= f" forall m f.
liftIO m >>= f = ConduitM (PipeM (liftM (unConduitM . f) (liftIO m)))
#-}
但是,当我尝试这样做时,我从GHC收到以下错误消息:
Data/Conduit/Internal/Conduit.hs:1025:84:
Could not deduce (Monad m) arising from a use of ‘liftM’
from the context (Monad (ConduitM i o m), MonadIO (ConduitM i o m))
bound by the RULE "ConduitM: liftIO x >>= f"
at Data/Conduit/Internal/Conduit.hs:1025:11-118
Possible fix:
add (Monad m) to the context of the RULE "ConduitM: liftIO x >>= f"
In the first argument of ‘PipeM’, namely
‘(liftM (unConduitM . f) (liftIO m))’
In the first argument of ‘ConduitM’, namely
‘(PipeM (liftM (unConduitM . f) (liftIO m)))’
In the expression:
ConduitM (PipeM (liftM (unConduitM . f) (liftIO m)))
Data/Conduit/Internal/Conduit.hs:1025:108:
Could not deduce (MonadIO m) arising from a use of ‘liftIO’
from the context (Monad (ConduitM i o m), MonadIO (ConduitM i o m))
bound by the RULE "ConduitM: liftIO x >>= f"
at Data/Conduit/Internal/Conduit.hs:1025:11-118
Possible fix:
add (MonadIO m) to the context of
the RULE "ConduitM: liftIO x >>= f"
In the second argument of ‘liftM’, namely ‘(liftIO m)’
In the first argument of ‘PipeM’, namely
‘(liftM (unConduitM . f) (liftIO m))’
In the first argument of ‘ConduitM’, namely
‘(PipeM (liftM (unConduitM . f) (liftIO m)))’
我不知道任何语法可以让我为重写规则指定这样的上下文。有没有办法实现这个目标?
答案 0 :(得分:9)
您可以在规则中指定具有约束的参数类型,例如
{-# RULES "ConduitM: liftIO x >>= f" forall m (f :: (Monad n, MonadIO n) => CounduitM i o n r).
liftIO m >>= f = ConduitM (PipeM (liftM (unConduitM . f) (liftIO m)))
#-}
(我没有对它进行过测试,因为我没有安装相关的软件包,但据我了解所涉及的类型,我认为应该可行。)
答案 1 :(得分:1)
我试图找出如何在重写规则中添加约束的类似效果。使用相同的语法我能够编译GHC,但显然,在这种情况下,重写规则将永远不会触发。
这是一个简单的例子:
#!/usr/bin/env stack
-- stack --resolver lts-7.14 exec -- ghc -O -ddump-rule-firings
module Main where
import Prelude as P
import System.Environment (getArgs)
class Num e => Power e where
(^:) :: Integral a => e -> a -> e
instance Power Double where
(^:) x y = go 0 1 where
go n acc | n < y = go (n+1) (acc*x)
| n > y = go (n-1) (acc/x)
| otherwise = acc
main :: IO ()
main = do
[xStr] <- getArgs
let x = read xStr :: Double
print (x ^ 24)
{-# RULES
"1. Test ^" forall (x :: Power x => x) n. x ^ n = x ^: n;
"2. Test ^" forall x n. (x :: Double) ^ n = x ^: n
#-}
即使删除了第二条规则,也不会触发第一条规则。 这是一个类似的SO问题,它解答了为什么它不会触发:GHC rewrite rule specialising a function for a type class