1

我有以下类型和声明:

import scalaz._, Scalaz._

trait Container[T] 
type FreeContainer[A] = Free[Container, A]
type FreeFreeContainer[A] = Free[FreeContainer, A]

val fc: FreeContainer[Int]
val ffc: FreeFreeContainer[Int]

val t: Container ~> Id

val tranformed: Int = fc.foldMap(t)   //ok
val tranformed2: Int = ffc.foldMap(t) //error

Container ~> Id有可能升到FreeContainer ~> Id吗?

4

1 回答 1

3

是的,通过foldMap

val t: Container ~> Id

val tt: FreeContainer ~> Id = new (FreeContainer ~> Id) {
  def apply[A](fc: FreeContainer[A]): A = fc.foldMap(t)
}

使用kind-projector 的多态 lambda 语法,这可以简化为

val tt: FreeContainer ~> Id = λ[FreeContainer ~> Id](_.foldMap(t))

所以你可以做

val tranformed2: Int = ffc.foldMap(λ[FreeContainer ~> Id](_.foldMap(t)))

或者,您可以只做两个连续foldMap的 s,第一个具有恒等自然变换:

val tranformed2: Int = ffc.foldMap(NaturalTransformation.refl[FreeContainer]).foldMap(t)
于 2018-03-06T12:22:16.447 回答