我可以自动实施课程吗? [英] Can I automatically implement classes?
问题描述
Monad
实例自动成为 Applicative
的一个实例。 implicit val listInstance = new Monad [List] {
def point [A](a:=> A )= List(a)
def bind [A,B](fa:List [A])(f:A => List [B])= fa flatMap f
}
列表(2)< *> List((x:Int)=> x + 1)//工作!
另一个例子: Arrow
自动为 Profunctor
。
然而,在Haskell中,我必须提供一个 Applicative
为每一个 Monad
反复。
是否可以避免这个重复的工作?
目前不可能,但如果您更改现有的库以支持此功能,打开DefaultSignatures会让你编写
class Applicative f其中
pure :: a - > f a
(*):: f(a - > b) - > f a - > f b
default pure :: Monad f => a - > f a
default(< *>):: Monad f => f(a - > b) - > f a - > fb
pure = return
(*)= ap
然后,一旦实现了实例Monad M,其中{ - ... - }
,一个简单的实例Applicative M
(with没有其中
或方法定义)将继承这些默认实现。我不确定为什么没有这样做。
In Scalaz every Monad
instance is automatically an instance of Applicative
.
implicit val listInstance = new Monad[List] {
def point[A](a: => A) = List(a)
def bind[A, B](fa: List[A])(f: A => List[B]) = fa flatMap f
}
List(2) <*> List((x: Int) => x + 1) // Works!
Another example: Arrow
is automatically a Profunctor
.
However, in Haskell I must provide an instance of Applicative
for every Monad
again and again.
Is it possible to avoid this repetitive job?
It isn't currently possible, though it would be if you changed the existing library to support this. Turning DefaultSignatures on would let you write
class Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
default pure :: Monad f => a -> f a
default (<*>) :: Monad f => f (a -> b) -> f a -> f b
pure = return
(<*>) = ap
Then once you had implemented instance Monad M where {- ... -}
, a simple instance Applicative M
(with no where
or method definitions) would inherit these default implementations. I'm not sure why this wasn't done.
这篇关于我可以自动实施课程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!