gpt4 book ai didi

haskell - 向类型类实例添加类约束

转载 作者:行者123 更新时间:2023-12-02 17:13:00 25 4
gpt4 key购买 nike

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

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

如何向实例添加适当的积分约束?我隐约感觉我可能需要修改 Pair 接口(interface)本身,但不知道该怎么做。

最佳答案

如果您有权访问类定义,则可以添加 Integral pi 的约束, k ,和l方法。不过,这有点令人不满意:没有任何说法 Integral将成为所有实例的正确约束,并且您毕竟不想仅仅因为没有足够的远见而拒绝某些实例。因此,这是一个概括:我们将允许约束在每个实例中有所不同。

{-# LANGUAGE ConstraintKinds, TypeFamilies #-}
import GHC.Exts

newtype CantorPair a = P { unP :: a }
cantorPair :: Integral a => a -> a -> CantorPair a
cantorUnpair :: Integral a => CantorPair a -> (a, a)
cantorPair = undefined
cantorUnpair = undefined

class Pair p where
type Ctxt p a :: Constraint
pi :: Ctxt p a => a -> a -> p a
k :: Ctxt p a => p a -> a
l :: Ctxt p a => p a -> a

instance Pair CantorPair where
type Ctxt CantorPair a = Integral a
pi = cantorPair
k = fst . cantorUnpair
l = snd . cantorUnpair

-- just for fun
data DataPair a = DataPair a a

instance Pair DataPair where
type Ctxt DataPair a = ()
pi = DataPair
k (DataPair a _) = a
l (DataPair _ a) = a

-- this one made GHC panic! neat, I get to file a bug
data Unit a = Unit

instance Pair Unit where
type Ctxt Unit a = a ~ ()
pi _ _ = Unit
k _ = ()
l _ = ()

关于haskell - 向类型类实例添加类约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12397751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com