gpt4 book ai didi

haskell - UndecidableInstances 和 newtypes

转载 作者:行者123 更新时间:2023-12-04 12:54:12 29 4
gpt4 key购买 nike

我有一个 UndecidableInstances我无法弄清楚如何避免使用 newtype 的问题.这是我最初的:

{-# LANGUAGE TypeFamilies, FlexibleContexts #-}

class Record r where
key :: r -> String

class (Record r) => SizedRecord r where
size :: r -> Int

class Database d where
type DBRecord d

class (Record a) => Agent a where
agentId :: a -> String
agentId = key

class (Database (UAgentDB u), Agent (UAgent u), Record (UAgent u))
=> Universe u where
type UAgent u
type UAgentDB u
-- plus other stuff

data SimpleUniverse d = SimpleUniverse
{
suDB :: d
-- plus other stuff
} deriving (Show, Eq)

instance (Record (DBRecord d)) => Universe (SimpleUniverse d) where -- line 28
type UAgent (SimpleUniverse d) = DBRecord d
type UAgentDB (SimpleUniverse d) = d
-- plus other stuff

我得到的信息是
amy9.hs:28:10:
Constraint is no smaller than the instance head
in the constraint: Record (DBRecord d)
(Use -XUndecidableInstances to permit this)
In the instance declaration for `Universe (SimpleUniverse d)'

我想避免 UndecidableInstances因为这段代码将在一个可重用的库中,所以我尝试声明一个 newtype :
newtype SimpleUniverse2 u = SimpleUniverse2 { fromAdditiveGroup :: u }

instance (Record (DBRecord u)) => Universe (SimpleUniverse2 u) where
type UAgent (SimpleUniverse2 u) = DBRecord u
type UAgentDB (SimpleUniverse2 u) = u
-- plus other stuff

但我得到同样的错误。我已阅读 UndecidableInstances 上其他问题的答案,但我无法解决这个问题。

最佳答案

作为一个可怕的组合,双重包装和使用FlexibleInstances似乎可以解决问题:

import Control.Monad.Identity    

instance (Database u, Agent (DBRecord u), Record (DBRecord u)) =>
Universe (Identity (Identity u)) where
type UAgent (Identity (Identity u)) = DBRecord u
type UAgentDB (Identity (Identity u)) = u

关于haskell - UndecidableInstances 和 newtypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23216619/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com