【问题标题】:Haskell Typeclass for Tuples元组的 Haskell 类型类
【发布时间】:2012-06-09 14:50:08
【问题描述】:

我在玩类型类并做了这个:

class Firstable f where
  fst :: f a -> a

class Secondable f where
  snd :: f a -> a

然后我尝试为(,) 添加一个实现并意识到我可以做到:

instance Secondable ((,) a) where
  snd (x,y) = y

我很确定这行得通,因为Secondable 应该有一种(* -> *),其中((,) a) 具有那种类型,但是,我不知道如何为((,) * a) 实现Firstable,其中* 是绑定变量,在我的解释中,我试图做相当于:

instance Firstable (flip (,) a) where ...

有没有办法在 Haskell 中做到这一点?最好不要扩展?

【问题讨论】:

  • AFAIK,不:您需要TypeSynonymInstances,但不能部分评估类型同义词。但是您知道MultiParamTypeClasses 的替代方案吗?这可能有点难看,但它确实有效。
  • 您可能对 tuple 包如何处理这个问题感兴趣:hackage.haskell.org/package/tuple

标签: haskell typeclass


【解决方案1】:

您可以像这样使用类型族(对 Edward 所写内容的不同看法):

{-# LANGUAGE TypeFamilies #-}

class Firstable a where
  type First a :: *
  fst :: a -> First a

class Secondable a where
  type Second a :: *
  snd :: a -> Second a

instance Firstable (a,b) where
  type First (a, b) = a
  fst (x, _) = x

instance Secondable (a,b) where
  type Second (a, b) = b
  snd (_, y) = y

【讨论】:

    【解决方案2】:

    MPTCS 和 Fundeps 或 TypeFamilies 可以提供参数保证更差的版本。

    type family Fst p
    type instance Fst (a,b) = a
    type instance Fst (a,b,c) = a
    

    ...

    class First p where
       fst :: p -> Fst p
    
    instance Fst (a,b) where
       fst (a,_) = a
    
    instance Fst (a,b,c) where
       fst (a,_,_) = a
    

    ...

    但最终,您需要使用一些扩展。

    【讨论】:

    • type instance Fst (a,b,c) = b 应该改为 type instance Fst (a,b,c) = a 吗?
    【解决方案3】:
    class Firstable f where
        fst :: f a b -> a
    
    class Secondable f where
        snd :: f a b -> b
    

    【讨论】:

    • 这种方式只能将 2 元组作为该类的实例,不是吗?这有点违背了开始使用类型类的目的。
    • @sepp2k 首先,他从未指定目的,我将其解释为他只是想概括(至少)两个参数的类型构造函数。其次,他的两个原始类具有完全相同的签名,这意味着他要么弄错了,要么他应该只使用一个类来描述这两个字段。
    • @GabrielGonzalez 是的,我希望元组能够用于 (,),(,,)...
    • 如果您愿意接受从右侧计数而不是从左侧计数,这种方法实际上会起作用,但我认为您不会让它反过来起作用。
    • 这是一个有趣的想法,虽然在这种情况下,你会想要这样做:fst :: f a -> a, snd :: f b a -> b, ...
    猜你喜欢
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    相关资源
    最近更新 更多