本文介绍了可以在新类型定义中使用类型类约束吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们具有以下newtype定义:

Suppose we have the following newtype definition:

newtype A = A { _run :: Monad m => A -> [Int] -> m Int }

这不能与GHC 8.0.2一起编译:

This does not compile with GHC 8.0.2:

error: Not in scope: type variable ‘m’

用像IO[]这样的具体类型类替换m确实可以编译,就像我期望的那样.既然可以,为什么GHC不允许上述签名?在此newtype内部添加类型类约束有什么问题?

Replacing m with a concrete typeclass like IO or [] does compile, as I would expect. Given that this is ok, why does GHC not allow the signature above? What is wrong with adding a typeclass constraint inside of this newtype?

推荐答案

这是可能的:

{-# LANGUAGE RankNTypes #-}
newtype A = A { _run :: forall m. Monad m => A -> [Int] -> m Int }

很难说出你想做什么,但这不是很有用.任何类型的A值都需要适用于所有monad(您无法选择).

It's hard to tell what you want to do, but this isn't very usable. Any value of type A needs to work for all monads (you don't get to choose).

在同样的限制下,这也是可能的:

This is also possible, with the same restrictions:

{-# LANGUAGE GADTs #-}
data A where A :: Monad m => (A -> [Int] -> m Int) -> A

但是也许你的意思更像是

But perhaps you mean something more like

newtype A m = A { _run :: A m -> [Int] -> m Int }

这允许使用不同的monad的不同类型的A值.

This allows for values of different types of A using different monads.

这篇关于可以在新类型定义中使用类型类约束吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 01:52
查看更多