简体   繁体   English

类型同义词的Typeclass实例

[英]Typeclass instance for type synonym

Afraid that I've grossly misunderstood types in Haskell. 害怕我严重误解了Haskell中的类型。 I'll get into it. 我会去的。 Say I have a type defined so: 说我有一个这样定义的类型:

type Vector = [Num a]

So I'm using a typeclass in the definition of the synonym. 所以我在同义词的定义中使用类型类。 Then if I want to add it to another typeclass, say Eq, maybe I would do something like so: 然后,如果我想将其添加到另一个类型类中,例如说Eq,也许我会这样做:

instance Eq Vector a where
  [] == [] = True
  [_]== [] = False
  [] == [_] = False
  (a : u) == (b : v) = (a == b) && (u == v)

But when I do this, GHC gives a 但是当我这样做时,GHC给出了

parse error on input '[' 解析输入'['上的错误

It's referring to the first left bracket in the line [_]== [] = False . 它指的是[_]== [] = False行中的第一个左括号。

Is this caused by an issue with my type definition? 这是由我的类型定义问题引起的吗?

There are several issues with this code, preventing it from being compiled. 此代码存在多个问题,导致其无法编译。 I think you mean that Vector is parameterized by the type a that it contains: 我认为您的意思是Vector由包含的类型a参数化:

type Vector a = [a]

I've dropped the Num constraint because it isn't needed for the rest of the example; 我删除了Num约束,因为在本示例的其余部分中不需要它。 I'll pick it up at the end. 我会在最后整理。

There's already an Eq instance for lists, so this is a bit of a dead end. 列表已经有一个Eq实例,所以这有点死胡同。 One way forward is to switch to a newtype: 前进的一种方法是切换到新类型:

newtype Vector a = Vector [a]

Unlike a type synonym declared with type , Haskell sees a newtype as a completely different type. 不像声明的类型代名词type ,哈斯克尔看到了newtype作为一个完全不同的类型。 A Vector is not a list, so we can define whatever type class instances we want. Vector不是列表,因此我们可以定义所需的任何类型类实例。

Our Eq instance gets a little longer, because we have to write the Vector constructor each time. 我们的Eq实例会更长一些,因为我们每次都必须编写Vector构造函数。 I added parentheses around Vector a in the first line. 我在第一行的Vector a周围加上了括号。

The only other change we need to make is adding the Eq a constraint before the instance. 我们需要做的唯一其他更改是在实例之前将Eq a添加Eq a约束。 In the last line of the definition, we compare the first element of the two Vectors . 在定义的最后一行,我们比较两个Vectors的第一个元素。 This only makes sense if the type a is an instance of Eq . 仅当类型aEq的实例时,这才有意义。

instance Eq a => Eq (Vector a) where
  Vector [] == Vector [] = True
  Vector [_] == Vector [] = False
  Vector [] == Vector [_] = False
  Vector (a : u) == Vector (b : v) = (a == b) && (Vector u == Vector v)

This compiles. 这样编译。 You could add a Num constraint, insisting that no one may construct a Vector a unless a is Num , or that Vector a is only Eq if a is Num . 你可以添加一个Num约束,坚持,没有人可以构建一个Vector a ,除非aNum ,或Vector a只有Eq ,如果aNum If this is something you want to do, I can add an example. 如果这是您想做的事情,我可以举个例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM