我应该使用类型类吗? [英] Should I use typeclasses or not?

查看:35
本文介绍了我应该使用类型类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解代码中何时使用和何时不使用 typeclass 时遇到了一些困难.当然,我的意思是创建我自己的,而不是使用已经定义的类型类.举个例子(非常愚蠢的例子),我应该这样做:

I have some difficulties to understand when use and when not use typeclass in my code. I mean create my own, and not use already defined typeclasses, of course. By example (very stupid example), should I do:

data Cars = Brakes | Wheels | Engine
data Computers = Processor | RAM | HardDrive  

class Repairable a where
    is_reparaible :: a -> Bool

instance Repairable Cars where
    is_repairable (Brakes) = True
    is_repairable (Wheels) = False
    is_repairable (Engine) = False

instance Repairable Computers where
    is_repairable (Processor) = False
    is_repairable (RAM)       = False
    is_repairable (HardDrive) = True

checkState :: (Reparaible a) => a -> ... 
checkState a = ...

(显然,这是一个愚蠢的、不完整的例子).

(Obviously, this is an stupid, incomplete example).

但这只是一点点用处,不是吗?为什么我不应该做一些简单的事情,只定义函数而不定义新的数据类型和类型类(及其实例).

But this is a lot for a little use, no? Why I shouldn't do something simple and only defining functions without defining new data types and typeclasses (with their instances).

这个例子太简单了,但实际上我在github上浏览Haskell代码的时候经常会看到类似的东西(新数据类型+类型类+实例),而不是只定义函数.

This example is too simple, but in facts I often see somethings like that (new data types+typeclasses+instances) when I browse Haskell code on github instead of only defining functions.

那么,什么时候应该创建新的数据类型、类型类等,什么时候应该使用函数?

So, when I should create new data types, typeclasses etc and when should I use functions?

谢谢.

推荐答案

为什么我不应该做一些简单的并且只定义函数的事情无需定义新的数据类型和类型类(以及它们的实例).

Why I shouldn't do something simple and only defining functions without defining new data types and typeclasses (with their instances).

为什么?你可以定义:

checkState :: (a -> Bool) -> (a -> b) -> (a -> b) -> a -> b
checkState is_repairable repairs destroy a
    = if (is_repairable a) then repairs a else destroy a

人们一直在滥用类型类.这并不意味着它是惯用的.

People misuse type classes all the time. It doesn't mean that it's idiomatic.

为了回答更一般的问题,这里有一些关于何时使用类型类以及何时不使用它们的经验法则:

To answer your more general question, here are some rules of thumb for when to use type classes and when not to use them:

在以下情况下使用类型类:

Use type classes if:

  • 每种给定的类型只有一种正确的行为

  • There is only one correct behavior per given type

类型类具有所有实例都必须满足的关联方程(即定律")

The type class has associated equations (i.e. "laws") that all instances must satisfy

在以下情况下不要使用类型类:

Don't use type classes if:

  • 您正在尝试命名空间.这就是模块和命名空间的用途.

  • You are trying to just namespace things. That's what modules and namespaces are for.

使用你的类型类的人无法在不查看实例源代码的情况下推断它的行为

A person using your type class cannot reason about how it will behave without looking at the source code of the instances

您发现您必须打开的扩展程序正在失控

You find that the extensions you have to turn on are getting out of control

这篇关于我应该使用类型类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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