haskell - 有没有一种简单的方法来引用具有约束参数的类型?

标签 haskell template-haskell type-variables

> {-# LANGUAGE TemplateHaskell #-}
> import Language.Haskell.TH
> import Control.Monad

假设我有一个类似 Default 的类

> class Default a where
>  def :: a

有一种直接的方法可以为也有 Monoid 实例的类型定义实例,比如

instance Monoid a => Default a where
  def = mempty

但由于存在重叠问题并且为了使其更易于控制,我们可能会提供一个 TH 宏。

(是的,我知道我们可以使用-XDerivingVia,我对这里的这种解决方案不感兴趣。)

> makeMonoidDefault :: Q Type -> DecsQ
> makeMonoidDefault instT = sequence
>   [ InstanceD Nothing [] <$> [t| Default $instT |] <*> [d|
>         $(varP $ mkName "def") = mempty |] ]

这可以很容易地用引用类型调用,比如

makeMonoidDefault [t| Maybe () |]

允许

*Main> def :: Maybe ()
Nothing

但这不允许像参数化实例这样的东西

instance Semigroup a => Default (Maybe a) where
  def = mempty

这可以用另一个宏来完成:

> makeMonoidDefault' :: Q (Cxt,Type) -> DecsQ
> makeMonoidDefault' cxtInstT = do
>  (cxt, instT) <- cxtInstT
>  sequence
>   [ InstanceD Nothing cxt <*> [t| Default $(pure instT) |] <*> [d|
>         $(varP $ mkName "def") = mempty |] ]

但是现在实际使用起来要尴尬得多:

makeMonoidDefault' $ do
   tParam <- pure . VarT <$> newName "a"
   sgcxt <- [t| Semigroup $tParam |]
   maybet <- [t| Maybe $tParam |]
   return ([sgcxt], maybet)

makeMonoidDefault' $ do
   tParam <- pure . VarT <$> newName "a"
   ((,) . (:[])) <$> [t| Semigroup $tParam |]
                 <*> [t| Maybe $tParam |]
  • 有没有一种方法可以在不显式使用 VarT 和应用组合器的情况下编写它,最好是在单引号中?
  • makeMonoidDefault' 的参数是否应该是 Q (Cxt, Type) 以外的东西?

最佳答案

我想到的一个 hacky 解决方案是这样的:

-- Quote.hs
{-# LANGUAGE TemplateHaskell #-}
module Quote where

import Language.Haskell.TH

class Default a where
  def :: a

makeMonoidDefault' :: Q Type -> DecsQ
makeMonoidDefault' q = do
  t <- q
  case t of
    ForallT _ cxt instT -> sequence
      [ InstanceD Nothing cxt <$> [t| Default $(pure instT) |] <*> [d|
            $(varP 'def) = mempty |] ]
    _ -> fail "<some nice error message>"

然后你可以像这样使用它:

-- Main.hs
{-# LANGUAGE TemplateHaskell, ExplicitForAll #-}
import Quote

makeMonoidDefault' [t|forall a. Semigroup a => Maybe a|]

main = pure ()

关于haskell - 有没有一种简单的方法来引用具有约束参数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67689333/

相关文章:

haskell - 这是 Haskell 类型推理的实际应用,还是其他什么?

sqlite - Haskell 变量 "not in scope: type variable ' m'"

haskell - 这是 Template Haskell 的预期行为吗?

java - 通用类创建

haskell - Free Pascal 有像 Haskell 那样的类型变量吗?

haskell - 两个延续如何相互抵消?

haskell - 了解 Purescript Eff Monad 和 do block

编译用 haskell 和模板 haskell 编写的共享对象并将其与 c 中的 main 链接

haskell - 存在量词默默地破坏了 Template Haskell (makeLenses)。为什么?

haskell - 约束的类型别名不与上下文共享相同的变量绑定(bind)行为