【问题标题】:Generic instance of custom type class in Haskell?Haskell中自定义类型类的通用实例?
【发布时间】:2013-11-25 10:17:57
【问题描述】:

假设我有以下数据结构:

data Dezi = Dezi1 Int | Dezi2 String | Dezi3 [Dezi] deriving(Show)

class TestInterface a where
    testInt :: a -> Dezi

instance TestInterface Int where
    testInt 0 = Dezi1 0
    testInt _ = Dezi2 "Nie nula"

instance Dezi a =>  TestInterface [a] where 
    testInt xs = Dezi3 $ map (\x -> testInt x) xs

在最后一条语句中,我正在尝试为我的类型类创建通用实例,我假设类型“a”是 Int 或 String,但编译器不满意:

`Dezi' is applied to too many type arguments
In the instance declaration for `TestInterface [a]'

我是初学者,仍在学习过程中。

谢谢!

【问题讨论】:

    标签: haskell generic-programming


    【解决方案1】:

    Dezi 是一种数据类型,而不是类型类。类型不是“Dezi 的实例”。相反,您可能会说类似

    instance TestInterface a => TestInterface [a] where
      testInt xs = Dezi3 $ map testInt xs
    

    这读起来像“要使as 的列表成为TestInterface 的实例,查找a 的实例并使用它。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      相关资源
      最近更新 更多