我有以下Haskell代码,可以完美编译:
import Control.Monad.Reader (Reader (..))
import Data.Coerce (Coercible, coerce)
data Flow i o = Flow (i -> o) (o -> i)
coerceFlow
:: (Coercible i i', Coercible o o')
=> Flow i o
-> Flow i' o'
coerceFlow = coerce
但是,如果我将Flow
类型的定义更改为以下内容:
data Flow i o = Flow (i -> Reader Int o) (o -> i)
我开始看到一个奇怪的错误:
Coerce.hs:10:14: error:
• Couldn't match type ‘o’ with ‘o'’ arising from a use of ‘coerce’
‘o’ is a rigid type variable bound by
the type signature for:
coerceFlow :: forall i i' o o'.
(Coercible i i', Coercible o o') =>
Flow i o -> Flow i' o'
at Coerce.hs:(6,1)-(9,17)
‘o'’ is a rigid type variable bound by
the type signature for:
coerceFlow :: forall i i' o o'.
(Coercible i i', Coercible o o') =>
Flow i o -> Flow i' o'
at Coerce.hs:(6,1)-(9,17)
• In the expression: coerce
In an equation for ‘coerceFlow’: coerceFlow = coerce
• Relevant bindings include
coerceFlow :: Flow i o -> Flow i' o' (bound at Coerce.hs:10:1)
|
10 | coerceFlow = coerce
| ^^^^^^
据我了解,我的数据类型不再自动为Coercible
。有没有办法告诉GHC我可以自动强制Flow
类型的值?我可以手动coerce
每个字段,但我想一次coerce
整个数据类型(这对于DerivingVia
起作用是必需的。)
我尝试使用RoleAnnotations
扩展名,如下所示:
type role Flow representational representational
但是我看到一个错误:
Coerce.hs:6:1: error:
• Role mismatch on variable o:
Annotation says representational but role nominal is required
• while checking a role annotation for ‘Flow’
|
6 | type role Flow representational representational
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我具有以下经过完美编译的Haskell代码:import Control.Monad.Reader(Reader(..))import Data.Coerce(Coercible,coerce)data Flow io = Flow(i-> o)(o-> i)coerceFlow ...
让我们调查: