[英]Fieldwise distribution of Monoid, Applicative, Monad etc for Haskell records
Is there a package that does roughly the following: 是否包含大致如下的包:
Given a record: 鉴于记录:
data R = R { a :: TypeA,
b :: TypeB,
c :: TypeC }
derives a lifted record: 得出一个解除记录:
data R_L f = R_L { a_L :: f TypeA,
b_L :: f TypeB,
c_L :: f TypeC }
and offers a couple of instances and functions similar to: 并提供了几个类似于以下的实例和功能:
instance (Monoid (f TypeA), Monoid (f TypeB), Monoid (f TypeC))
=> (Monoid (R_L f)) where
mempty = R_L mempty mempty mempty
mplus a b = ...fieldwise mplus...
sequenceR :: (Monad m) => R_L m -> m R
sequenceR = ... run fields, sum results ...
sequenceRA :: (Applicative m) => R_L m -> m R
sequenceRA x = R <$> a_L x <*> b_L x <*> c_L x
and probably others. 可能还有其他人。 Is there a package that provides this functionality and when not, which of the mechanisms (TH? Generics?) is best to use to implement it? 是否有提供此功能的软件包,何时不提供哪种机制(TH?Generics?)最适合实现它?
The monoid part is possible with generic-deriving , which offers an alternative GMonoid
, of which generics are automatically an instance. 使用泛型派生可以实现幺半群部分,它提供了替代的GMonoid
,其中泛型自动成为实例。
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts, DefaultSignatures #-}
import Data.Monoid
import qualified Generics.Deriving.Monoid as M
data R_L f = R_L { a :: f [()],
b :: f String,
c :: f () } deriving (Generic)
Now you can do the following: 现在您可以执行以下操作:
*Main> let x = R_L (Just [()]) Nothing (Just ()) `M.gmappenddefault` R_L (Just [()]) (Just "foo") (Just ())
*Main> a x
Just [(),()]
*Main> b x
Just "foo"
*Main> c x
Just ()
(I am still figuring out the generic Show
instance.) (我还在搞清楚通用的Show
实例。)
An ordinary Monoid
instance can be created as follows (thought, that might be called boilerplate again...): 可以如下创建普通的Monoid
实例( Monoid
,可能再次称为样板文件......):
instance (Monoid (f [()]), Monoid (f String), Monoid (f ())) => Monoid (R_L f) where
mempty = M.memptydefault
mappend = M.mappenddefault
In the package, there are also other derived instances for Functor
, Traversable
and Foldable
. 在包中,还有Functor
, Traversable
和Foldable
其他派生实例。
Monad
and Applicative
can maybe be modelled with generics similar to the existing instances, if you change the kind of your type ; 如果您更改类型的类型 ,可以使用与现有实例类似的泛型建模Monad
和Applicative
; although, maybe not in the way you like, since, I think, they would only make sense as a product functor of the fields' types, and not as you propose. 虽然,也许不是你喜欢的方式,因为,我认为,它们只会作为田地类型的产品函子而有意义,而不是你提出的那样。
In the true open source spirit I wrote my own library: 在真正的开源精神中,我编写了自己的库:
http://hackage.haskell.org/package/fieldwise http://hackage.haskell.org/package/fieldwise
https://github.com/gracjan/fieldwise https://github.com/gracjan/fieldwise
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.