Lan*_*dei 11 haskell typeclass
我知道有fst和snd,但为什么会出现使用类型类,存取函数没有"一般"的定义?我会建议像
class Get1 p a | p -> a where
get1 :: p -> a
instance Get1 (a,b) a where
get1 (x,_) = x
instance Get1 (a,b,c) a where
get1 (x,_,_) = x
class Get2 p a | p -> a where
get2 :: p -> a
instance Get2 (a,b) b where
get2 (_,x) = x
instance Get2 (a,b,c) b where
get2 (_,x,_) = x
Run Code Online (Sandbox Code Playgroud)
当然,你需要为这个有些语言扩展,但不是这个多少更方便的这样呢?特别是您可以为自己的类型添加实例.
有一点要注意的是,fst与snd只允许一个观看到2元组.将它们推广到其他智能和操作很快就会变得很痛苦.如果你也想,例如,映射一个数组的第一个元素,你必须引入另一个组合子(其中,备案,存在2元组的Control.Arrow.first).这很快导致高级元组的组合器数量激增.
话虽这么说,lens提供了一些很好的工具来处理元组.Control.Lens.Tuple提供了几种折射率透镜_1,_2等,其允许访问元组的第一,第二等元素,直到元数9.
例如,
>>> import Control.Lens
>>> let t = (1,2,3,5,6,7,2)
>>> t ^._1
1
>>> t & _1 .~ 'a'
('a',2,3,5,6,7,2)
>>> t & _1 +~ 41
(42,2,3,5,6,7,2)
>>> over _1 (+1) t
(2,2,3,5,6,7,2)
Run Code Online (Sandbox Code Playgroud)
您可能也对in中的元组实例感兴趣Control.Lens.At.此外,该tuple-lenses 软件包还提供了一些更通用的镜头,用于一次检查多个元组条目.