在新类型中包装类型

问题描述 投票:0回答:1

在以下代码中,我得到了警告Orphan instance: instance (MonadIO m, Monad m) => GenerateUUID m

instance (MonadIO m, Monad m) => GenerateUUID m where
  generateUUID = liftIO nextRandom

据此解决方案是

        move the instance declaration to the module of the class or of the type, or
        wrap the type with a newtype and declare the instance on the new type.

((或禁用警告帽,Internet也建议)

我的问题是我找不到如何用新类型包装类型?

haskell ghc
1个回答
0
投票

会是类似的东西

newtype Foo m = Foo { unFoo :: m }

instance (MonadIO m, Monad m) => GenerateUUID (Foo m) where
    generateUUID = liftIO nextRandom

为了避免孤立实例警告,您的实例声明必须伴随以下至少一项:

  1. 正在实例化的类
  2. 要为其定义实例的类型的定义。

定义newtype满足第二个条件,尽管使用实例可能会更加复杂。

© www.soinside.com 2019 - 2024. All rights reserved.