元组的 Haskell 类型类

标签 haskell typeclass

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

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)有那个类型,但是我不知道如何实现Firstable对于 ((,) * a)在哪里 *是绑定(bind)变量,在我的解释中,我试图做相当于:
instance Firstable (flip (,) a) where ...
有没有办法在 Haskell 中做到这一点?最好没有扩展?

最佳答案

您可以像这样使用类型族(对 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

关于元组的 Haskell 类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899804/

相关文章:

F# 类型约束和重载解析

haskell - 在 haskell 中编写仅适用于关联类型的函数

scala - 如何避免具有多个类型类关系的模棱两可的转换链?

haskell - 如何在 Haskell 中使记录类型位可寻址?

haskell - 在定义之前使用符号

haskell - 无法在 Haskell 中获取列表的长度

haskell - 为什么将数据类型作为约束添加到类型声明会导致匹配错误而不是更正确的错误?

json - Haskell Aeson 解析混合元素数组

haskell - 从自定义类型创建随机数据

haskell - 以组合方式将异构提升类型反射回值