我正在使用 free 和 compdata 包(在精神上类似于 Combining Free types )构建几个 DSL,这些 DSL 应该是基于“免费 monad”和“点菜数据类型”可组合的。
虽然这适用于一些简单的 DSL,但我坚持使用具有类型参数的 DSL,在不依赖此类型参数的构造函数/命令的情况下,会导致 GHC 产生不明确的类型参数错误。
为了澄清,这里有一些代码:
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
module DSL where
import Data.Comp
import Control.Monad.Free
type Index = Int
data DSL a next = Read Index (a -> next)
| Write a (Index -> next)
| GetLastIndex (Index -> next)
deriving (Functor)
read :: (Functor f, DSL a :<: f, MonadFree f m) => Index -> m a
read idx = liftF (inj (Read idx id))
write :: (Functor f, DSL a :<: f, MonadFree f m) => a -> m Index
write a = liftF (inj (Write a id))
-- This works
getLastIndex' :: MonadFree (DSL a) m => m Index
getLastIndex' = liftF (GetLastIndex id)
-- This doesn't:
--
-- Could not deduce (Data.Comp.Ops.Subsume
-- (compdata-0.10:Data.Comp.SubsumeCommon.ComprEmb
-- (Data.Comp.Ops.Elem (DSL a0) f))
-- (DSL a0)
-- f)
-- from the context (Functor f, DSL a :<: f, MonadFree f m)
-- bound by the type signature for
-- getLastIndex :: (Functor f, DSL a :<: f, MonadFree f m) => m Index
-- at simple.hs:30:17-66
-- The type variable ‘a0’ is ambiguous
-- In the ambiguity check for the type signature for ‘getLastIndex’:
-- getLastIndex :: forall (m :: * -> *) (f :: * -> *) a.
-- (Functor f, DSL a :<: f, MonadFree f m) =>
-- m Index
-- To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
-- In the type signature for ‘getLastIndex’:
-- getLastIndex :: (Functor f, DSL a :<: f, MonadFree f m) => m Index
getLastIndex :: (Functor f, DSL a :<: f, MonadFree f m) => m Index
-- getLastIndex = liftF (inj (GetLastIndex id))
getLastIndex = _
试图通过启用 GHC 暗示的 AllowAmbiguousTypes 扩展来使其工作并没有让我更进一步。我尝试在类型签名中添加一些 forall a 风格的东西,但无济于事。
有没有办法让这种模式起作用?
最佳答案
这是一个相对众所周知的“点菜”开放金额限制。
简而言之,如果我们有一个 f
仿函数,它本身具有一个或多个内部类型索引,那么类型推断对于包含该仿函数的开放和会受到很大影响。
说明原因,假设我们有一个包含 DSL ()
和 DSL Int
的未结和。 GHC 必须为其中之一选择一个实例,但 getLastIndex
不可能,因为参数或返回类型中未提及 a
参数。 GHC 基本上没有上下文中关于 a
的信息。
这可以使用 Data.Proxy
以一种有点笨拙的方式来补救:
import Data.Proxy
getLastIndex ::
forall a f m.
(Functor f, DSL a :<: f, MonadFree f m)
=> Proxy a -> m Index
getLastIndex _ = liftF (inj (GetLastIndex id :: DSL a Index))
或者,如果我们要求开和中只有一个
DSL
,我们可以恢复良好的类型推断和明确性。然而,这涉及为
:<:
之类的仿函数(具有内部类型索引的仿函数)重写类型级查找代码。我们真的不能用 DSL
来做到这一点,因为它不导出相关的 type-level machinery.我写了一个 minimal example 上面的实现对于你的情况是什么样的。我不把它贴在这里,因为它有点长而且没有启发性。请注意,内部索引的选择完全由仿函数的构造函数和开放总和决定。这也修复了其他情况的类型推断;例如,对于旧代码,如果
compdata
是数字文字或任何多态值,我们必须对 Write x f
的每次使用进行类型注释,而在新代码中,它被推断出来。另外,请注意示例实现仅适用于具有单个内部索引的仿函数!如果我们想要一个
x
,那么我们也必须为这种情况编写新代码,或者改用 DSL a b next
。关于haskell - 处理可组合的免费 DSL 中的歧义类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30058292/