Cha*_*ham 15 haskell typeclass
我正在玩类型类,并做了这个:
class Firstable f where
fst :: f a -> a
class Secondable f where
snd :: f a -> a
Run Code Online (Sandbox Code Playgroud)
然后我尝试为(,)添加一个实现,并意识到我可以这样做:
instance Secondable ((,) a) where
snd (x,y) = y
Run Code Online (Sandbox Code Playgroud)
我很确定这是有效的,因为Secondable应该有类型(* - >*)其中((,)a)具有该类型,但是,我不知道如何为((,)*a)实现Firstable,其中*是绑定变量,在我的解释中,我试图做相当于:
instance Firstable (flip (,) a) where ...
Run Code Online (Sandbox Code Playgroud)
在Haskell有办法做到这一点吗?最好没有延期?
谢谢!
dfl*_*str 10
你可以像这样使用类型系列(对爱德华写的不同):
{-# 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
Run Code Online (Sandbox Code Playgroud)
MPTCS 和 Fundeps 或 TypeFamilies 可以提供参数性保证较差的版本。
type family Fst p
type instance Fst (a,b) = a
type instance Fst (a,b,c) = a
Run Code Online (Sandbox Code Playgroud)
...
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
Run Code Online (Sandbox Code Playgroud)
...
但最终,您需要使用一些扩展。
| 归档时间: |
|
| 查看次数: |
2548 次 |
| 最近记录: |