实例在 Haskell 中是什么意思? [英] What does instance mean in Haskell?

查看:41
本文介绍了实例在 Haskell 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在面向对象的语言(例如 Java 和 Python)中,我们可以从类中创建对象/实例.在 Haskell 中,我们可以从类型类中创建实例,例如:

In object-oriented languages (e.g; Java and Python) we can make objects/instances from classes. In Haskell we can make instances from type-classes, ex:

data ShirtSize = S | M | L      -- Here ShirtSize is a enum data-type

class MyEq a where
  (==) :: a -> a -> Bool
instance MyEq ShirtSize where   -- Here ShirtSize is an instance of the MyEq type-class
  S == S = True
  M == M = True
  L == L = True
  _ == _ = False

我的问题是:实例在haskell中是什么意思?在 Java 中,我们可以从类中创建实例,但在 Haskell 中,实例似乎是类型(如 ShirtSize),您可以在其上应用类型类函数(例如 MyEq 中的 (==) 函数).我对吗?以及与 Java 中的实例/对象相比,Haskell 中的实例是什么?

My question is: What does instance mean in haskell? In java we can make instances from classes, but in haskell it seems like instances are types (like ShirtSize) which you can apply type-class functions on (e.g the (==) function from MyEq). Am I right? and also what is an instance in Haskell compared to an instance/object in Java?

推荐答案

在 Java 中,类系统是一种将相似对象分组的方法.类的实例是属于该类的单个对象.

In Java, the class system is a way to group similar objects. An instance of a class is an individual object which belongs to that class.

在 Haskell 中,类系统(粗略地说)是一种对相似类型进行分组的方法.(这就是我们称它们为类型类"的原因).类的实例是属于该类的单个类型.(也就是说,直到您开始考虑多参数类型类).

In Haskell, the class system is (roughly speaking) a way to group similar types. (This is the reason we call them "type classes"). An instance of a class is an individual type which belongs to that class. (That is, until you start considering multiparametric type classes).

顺便说一下,Haskell(单参数)类有点类似于 Java 接口,并且通过扩展,类似于 Java 类.或者 Haskell 实例可能类似于 Java 类.最好将此视为巧合.处理这个术语时要记住它的数学起源.一个类只是一堆属于一起的东西,而一个实例就是其中的一个.

Incidentally, a Haskell (monoparametric) class somewhat resembles a Java interface and, by extension, a Java class. Or perhaps a Haskell instance resembles Java class. It's better to view this as a coincidence. Approach the term keeping its mathematical origins in mind. A class is just a bunch of things that belong together, and an instance is one of these things.

这篇关于实例在 Haskell 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆