【问题标题】:In Haskell, is it possible to provide default implementation for partially applied multi-param type class?在 Haskell 中,是否可以为部分应用的多参数类型类提供默认实现?
【发布时间】:2017-12-18 16:01:44
【问题描述】:

例如,我有一个类型类:

class MyClass a b c where
    fun01 :: a -> b
    fun02 :: a -> c

    fun03 :: a -> b -> c -> ()
    fun04 :: a -> WhatEver

我想为我提供一个默认实现,我们称它为BaseDataType,它定义了fun03 的实现自身以及fun01 和fun02。然后我会有这样的东西:

class MyClass BaseDataType b c where
    fun03 = fun01 <$> fun02 ...
    fun04 = fun02 ...

除了完成我的类实例并避免 fun03 和 fun04 的所有样板代码之外,我只提供 fun01 和 fun02 就像这样:

instance MyClass BaseDataType Int Char where
    fun01 = 1
    fun02 = 'C'

是否可能有一些语言扩展允许这种行为?我找不到有关此主题的任何内容。

【问题讨论】:

    标签: haskell default typeclass multiparameter


    【解决方案1】:

    没有这样的扩展,但是你可以通过将你的类分成两个类来实现这个功能:

    class MyClass1 a b c where
        fun03 :: a -> b -> c -> ()
        fun04 :: a -> WhatEver
    
    class MyClass1 a b c => MyClass2 a b c where    
        fun01 :: a -> b
        fun02 :: a -> c
    

    然后您的实例将按照您想要的方式工作:

    -- NB: need the MyClass2 constraint if you use `fun01` or `fun02` in the definitions
    -- This requires UndecidableInstances
    instance MyClass2 BaseDataType b c => MyClass1 BaseDataType b c where
        fun03 = fun01 <$> fun02 ...
        fun04 = fun02 ...
    
    instance MyClass2 BaseDataType Int Char where
        fun01 = 1
        fun02 = 'C'
    

    您班级的用户不受影响;他们可以继续使用之前使用MyClass 的MyClass2 并获得完全相同的功能。


    顺便说一句:MyClass 的原始定义,MyClass1 和 MyClass2 甚至由于几个模棱两可的类型错误而无法编译(c 在fun01 的类型中没有提及等) - 我假设这个类只是为了演示目的而定义的,我没有尝试解决这个问题。

    【讨论】:

      【解决方案2】:

      你可以像这样使用 DefaultSignatures

      class MyClass a b c where
          fun01 :: a -> b
          fun02 :: a -> c
      
          fun03 :: a -> b -> c -> ()
          default fun03 :: (a ~ BaseDataType) => a -> b -> c -> ()
          fun03 = fun01 <$> fun02 ...
      
          fun04 :: a -> WhatEver
          default fun04 :: (a ~ BaseDataType) => a -> WhatEver
          fun04 = fun02 ...
      

      【讨论】:

      • +1,但我认为这不适用于 OP,因为默认值是 for all MyClass 实例,而不仅仅是 MyClass BaseDataType 专业化。 (在其他情况下,默认实现只会给出一个模糊的类型错误,以指示必须替换自定义实例。)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多