简体   繁体   English

不能将等式约束表示为自定义约束

[英]Cannot represent equality constraint as a custom constraint

I have a function type declaration我有一个 function 类型声明

f :: MonadHandler m => SqlPersistT m ()

Which I want to convert to我想转换成

f :: MonadHandlerDB m => m ()

I try everything I can think of to define constraint MonadHandlerDB, but cannot get either it or function type declaration to compile, eg:我尝试了我能想到的一切来定义约束 MonadHandlerDB,但无法获得它或 function 类型声明来编译,例如:

class (forall a . (MonadHandler m, m ~ SqlPersistT a)) => MonadHandlerDB m

class MonadHandlerDB m
instance MonadHandler a => MonadHandlerDB (SqlPersistT a)

type MonadHandlerDB m = forall a . (MonadHandler a, m ~ SqlPersistT a)

type MonadHandlerDB = forall a . (MonadHandler a => m ~ SqlPersistT a)

type MonadHandlerDB m = forall a . (MonadHandler a => m ~ SqlPersistT a)

One of the errors:错误之一:

Couldn't match type `m' with `ReaderT backend0 m0
`m' is a rigid type variable bound by
the type signature for:
  f:: forall (m :: * -> *).
      MonadHandlerDB m =>
      m ()

SqlPersistT is defined as SqlPersistT 定义为

type SqlPersistT = ReaderT SqlBackend

How do I express this constraint?我如何表达这个约束?

I think this achieves what you want:我认为这可以实现您想要的:

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}

import Control.Monad.Trans.Reader (ReaderT (ReaderT))
import Database.Persist.Sql (SqlPersistT)
import Yesod.Core (MonadHandler)

f :: MonadHandlerDB m => m ()
f = undefined

class (MonadHandler (Sub m), m ~ SqlPersistT (Sub m)) => MonadHandlerDB m where
  type Sub m :: * -> *

instance MonadHandler m => MonadHandlerDB (SqlPersistT m) where
  type Sub (SqlPersistT m) = m

But note that I think this is really not very good to use in practice.但请注意,我认为这在实践中真的不是很好用。 It makes it seem as if the m is completely polymorphic, but, in fact, it can only ever be some monad inside SqlPersistT .它看起来好像m是完全多态的,但实际上,它只能是SqlPersistT中的某个 monad。

Constraints are powerful, but I think a constraint like this has a high potential to confuse its users.约束很强大,但我认为像这样的约束很可能会混淆它的用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM