本文介绍了如何为 scalaz 的 Functor 提供一个具有上下文绑定的高级类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为以下类定义一个 Functor 实例:

I want to define a Functor instances for the following classes:

class RequiresManifest[A: Manifest] {
  def value: A
}

class RequiresAnyRef[A <: AnyRef] {
  def value: A
}

class RequiresBothManifestAndAnyRef[A <: AnyRef: Manifest] {
  def value: A
}

这可能吗?或者可以定义一个 'BoundedFunctor trait 吗?像这样:

Is this possible ? Alternatively can a 'BoundedFunctor trait be defined ? something like this:

trait BoundedFunctor[F[_], Bound[_]] {
  def fmap[A: Bound, B: Bound](r: F[A], f: A => B): F[B]
}

这是我的激励示例:如何为 TypedConverter 类定义函子.

Here's my motivating example: How can I defined a Functor for the class TypedConverter.

import com.thoughtworks.xstream.converters.Converter

abstract class TypedConverter[A <: AnyRef: Manifest] extends Converter { 
  final def canConvert(klass: Class[_]) = 
    manifest[A].erasure.isAssignableFrom(klass)

  final def marshal(value: AnyRef, writer: HierarchicalStreamWriter, 
                    context: MarshallingContext) =
    typedMarshal(value.asInstanceOf[A], writer, context)

  final def unmarshal(reader: HierarchicalStreamReader, 
                      context: UnmarshallingContext) = 
    typedUnmarshal(reader, context)

  def typedMarshal(value: A, writer: HierarchicalStreamWriter, 
                   context: MarshallingContext): Unit

  def typedUnmarshal(reader: HierarchicalStreamReader, 
                     context: UnmarshallingContext): A
}

这种更高级的类型对其类型参数有两个约束,第一个是 Manifest,因为它用于 'canConvert' 的实现,第二个是 AnyRef,因为解组需要一个对象.

This higher-kinded type has two constraints on its type parameter, first Manifest because that's used in the implementation of 'canConvert', second AnyRef because unmarshal requires an Object.

实际上我正在尝试创建一个 InvariantFunctor,但 Functor 会从一开始就这样做.

Actually I'm trying to create an InvariantFunctor, but Functor will do to start with.

推荐答案

请注意,在数学中,函子是从一个类别到另一个类别的映射.在 Comp Sci 中,人们以某种​​方式相信函子是内函子,例如对于 Scala 话语,它定义在所有 Scala 类型上.

See, in Math, a functor is a mapping from one category to another. In Comp Sci somehow people believe a functor is an endofunctor, e.g. for Scala discourse, it is defined on all Scala types.

scalaz 的实现就是这样编写的.

That's how scalaz's implementation is written.

但不一定是这样.据我了解,在您的情况下,您有一个子类别(大致由 Bound 定义);所以函子将从 Bound 到 Scala.

But it does not have to be so. As I understand, in your case you have a subcategory (roughly defined by Bound); so the functor will be from Bound to Scala.

总的来说,这是一个好主意,没有太多探索.我相信我们必须进一步调查此事.尽管在编程语言中明确定义类别有点问题.甚至不确定 Agda.

It is a good idea in general, not much explored. I believe we have to go investigate this further. It is a little bit problematic though to explicitly define categories in programming languages. Not even sure about Agda.

这篇关于如何为 scalaz 的 Functor 提供一个具有上下文绑定的高级类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:43