我在玩类型类并做了这个:
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/