我可以自动实施课程吗? [英] Can I automatically implement classes?

查看:104
本文介绍了我可以自动实施课程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scalaz中,每个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆