向 typeclass 实例添加类约束 [英] Adding class constraints to typeclass instance

查看:33
本文介绍了向 typeclass 实例添加类约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现康托配对函数,作为泛型 Pair 类型类,如下所示:

I'm trying to implement the Cantor Pairing Function, as an instance of a generic Pair typeclass, as so:

module Pair (Pair, CantorPair) where

-- Pair interface
class Pair p where
    pi :: a -> a -> p a
    k :: p a -> a
    l :: p a -> a

-- Wrapper for typing
newtype CantorPair a = P { unP :: a }

-- Assume two functions with signatures:
cantorPair :: Integral a => a -> a -> CantorPair a
cantorUnpair :: Integral a => CantorPair a -> (a, a)

-- I need to somehow add an Integral a constraint to this instance,
-- but I can't work out how to do it.
instance Pair CantorPair where
    pi = cantorPair
    k = fst . cantorUnpair
    l = snd . cantorUnpair

如何向实例添加适当的 Integral 约束?我有一种模糊的感觉,我可能需要修改 Pair 接口本身,但不知道该怎么做.

How can I add the appropriate Integral constraint to the instance? I have a vague feeling I might need to modify the Pair interface itself, but not sure how to go about this.

推荐答案

您是否希望所有对始终包含整数元素?在这种情况下,您可以将约束添加到方法的签名中:

Do you want all pairs to always contain integral elements? In this case, you could add the constraint to the signatures of the methods:

class Pair p where
  pi :: Integral i => i -> i -> p i
  k :: Integral i => p i -> i
  l :: Integral i => p i -> i

这将使您的配对类不那么通用,但会确保您的 CantorPair 类型可以成为其中的一部分.

This will make you pair class less general but will ensure that your CantorPair type could be a part of it.

如果您想让 Pair 类保持某种通用性,您可以使用多参数类型类.(这将需要两个扩展:MultiParamTypeClassesFlexibleInstances.)

If you want to keep your Pair class somewhat general, you could use a multi parameter type class. (This will require two extensions: MultiParamTypeClasses and FlexibleInstances.)

class Pair p a where
  pi :: a -> a -> p a
  k :: p a -> a
  l :: p a -> a

instance Integral i => Pair CantorPair i where
    pi = cantorPair
    k = fst . cantorUnpair
    l = snd . cantorUnpair

从设计的角度来看,我不知道这是否一定是最佳选择,但这是了解多参数类型类如何工作的好方法.(诚​​然,这相当简单.)

I don't know if this is necessarily the best option from a design standpoint, but it's a good way to learn about how multiparamter type classes work. (Which, admittedly, is fairly simple.)

这篇关于向 typeclass 实例添加类约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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