简体   繁体   English

永久类型的“永远”组合器

[英]`forever` Combinator with Higher Kinded Type

I'm trying to run the following combinator from Functional Programming in Scala : 我正在尝试从Scala的Functional Programming中运行以下组合器:

trait AddlCombinators[F[_]] extends Monad[F[_]] {
  def forever[A, B](a: F[A]): F[B] = {
    lazy val t: F[B] = forever(a)
    a flatMap (_ => t)
  }
}

But it's not compiling: 但是它没有编译:

[error] AddlCombinators.scala:7: value flatMap is not a member of type 
      parameter F[A]
[error]     a flatMap (_ => t)
[error]       ^

My understanding is that I need to use F[_] as it denotes a higher kinded type. 我的理解是,我需要使用F[_]因为它表示更高种类的类型。

For example, I had written a Monad[List] in a past chapter of this book: 例如,我在本书的上一章中写了Monad[List]

object ListMonad extends Monad[List] {
  def unit[A](a: => A): List[A] = List(a)

  def flatMap[A,B](ma: List[A])(f: A => List[B]): List[B] =
    ma.map(x => f(x)).flatten
}

EDIT Adding Monad and Functor code 编辑添加MonadFunctor代码

trait Functor[F[_]] {
  def map[A,B](fa: F[A])(f: A => B): F[B]
}

trait Monad[F[_]] extends Functor[F] {
    def unit[A](a: => A): F[A]
    def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B]

How can I resolve the above compile-time error? 如何解决上述编译时错误? Also, what is the meaning of F[_] as the type to AddlCombinators and Monad ? 另外, F[_]作为AddlCombinatorsMonad的类型是什么意思? Can a general "higher kinded type" be used? 可以使用一般的“高级类型”吗?

a flatMap (_ => t) is the culprit here. 罪魁祸首是a flatMap (_ => t)

As per the code given, you can use flatMap(a)(_ => t) to get it compiling. 按照给定的代码,您可以使用flatMap(a)(_ => t)进行编译。

Monad interface does not automatically add monadic operators to any parameterised type unless you use implicits. 除非您使用隐式,否则Monad接口不会自动将Monadic运算符添加到任何参数化类型。

F[_] is an existential type which means that F is a type which contains some other type, equivalent to: trait F {type A} . F[_]是存在类型,这意味着F是包含其他类型的类型,等效于: trait F {type A} Every Monad is a Functor, and only parameterised types can be Functors, which is why you need to parameterize Monads with F[_] . 每个Monad都是一个Functor,只有参数化类型可以是Functors,这就是为什么您需要使用F[_]来参数化Monad的原因。 Put another way, only paratmeterized types can satisfy Monad/Functor interface. 换句话说,只有参数化类型才能满足Monad / Functor接口。 A type parameterized by a parameterized type (* -> *) -> * is a higher kinded type. 通过参数化类型(* -> *) -> *参数化的类型是更高种类的类型。 F[_] is the least restrictive, hence most general type that can be used here. F[_]是限制性最小的,因此可以在这里使用的最通用的类​​型。 Other paramterized types can be made to look like F[_] via type projections. 通过类型投影,可以使其他参数化的类型看起来像F [_]。 For example, to define a Monad for a right biased Either type, you can use type FA = ({type l[a] = Either[L, a]})#l as F[_] . 例如,要为右偏的Either类型定义Monad,可以使用type FA = ({type l[a] = Either[L, a]})#l作为F[_] See here for complete code for Monad for Either. 请参阅此处,以获取Monad for Either的完整代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM